note 98025 added to function.array-merge
| From: | me at cafuego dot net | Date: | Fri, 21 May 2010 04:49:15 +0000 |
| Subject: | note 98025 added to function.array-merge | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-169480@lists.php.net to get a copy of this message | ||
<?php
function array_merge_zipper(&$output, $one = array(), $two = array(), $same_size= TRUE) {
if ($same_size) {
// Return FALSE if the arrays differ in size.
if (count($one) != count($two))
return FALSE;
$number = count($one);
} else {
// Count as high as the smallest array.
$number = min(count($one), count($two));
}
// Empty the output array.
$output = array();
// Merge.
for ($i = 0; $i < $number; $i++) {
$output[] = $one[$i];
$output[] = $two[$i];
}
// Return success.
return TRUE;
}
?>
This function merges two arrays into one, alternating between the two arrays. Given:
$one = array('apple', 'pear');
$two = array('blue', 'red');
$output = array();
array_merge_zipper(&$output, $one, $two, TRUE);
$output would be:
array(
0 => 'apple',
1 => 'blue',
2 => 'pear',
3 => 'red'
);
The $same_size flag is to note whether both input arrays contain the same number of items. If not,
setting the flag to FALSE will make the function merge up to the number of items in the smallest of
the two input arrays.
The following function does essentially the same, but preserves array keys. It'll return FALSE
if the input arrays share a key between them or if the arrays differ in size.
<?php
function array_merge_zipper_key(&$output, $one = array(), $two = array()) {
// Return FALSE if the arrays differ in size.
if (count($one) != count($two))
return FALSE;
// Returns FALSE if the arrays share a key.
if (count(array_keys_intersect($one, $two)))
return FALSE;
// Empty the output array.
$output = array();
// keys!
$one_keys = array_keys($one);
$two_keys = array_keys($two);
// Merge.
for ($i = 0; $i < count($one); $i++) {
$output[$one_keys[$i]] = $one[$one_keys[$i]];
$output[$two_keys[$i]] = $two[$two_keys[$i]];
}
// Return success.
return TRUE;
}
----
Server IP: 117.104.162.229
Probable Submitter: 150.101.221.106
----
Manual Page -- http://www.php.net/manual/en/function.array-merge.php
Edit -- https://master.php.net/note/edit/98025
Del: integrated -- https://master.php.net/note/delete/98025/integrated
Del: useless -- https://master.php.net/note/delete/98025/useless
Del: bad code -- https://master.php.net/note/delete/98025/bad+code
Del: spam -- https://master.php.net/note/delete/98025/spam
Del: non-english -- https://master.php.net/note/delete/98025/non-english
Del: in docs -- https://master.php.net/note/delete/98025/in+docs
Del: other reasons-- https://master.php.net/note/delete/98025
Reject -- https://master.php.net/note/reject/98025
Search -- https://master.php.net/manage/user-notes.php