note 122017 added to ref.array
| From: | LawrenceDOliveiro@php.net | Date: | Wed, 13 Dec 2017 04:38:26 +0000 |
| Subject: | note 122017 added to ref.array | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-209359@lists.php.net to get a copy of this message | ||
*Beware* that there is no proper built-in array-concatenation function. Consider the following two
arrays:
$arr1 = array(1, 2);
$arr2 = array("red", "green", "blue");
If you try
print_r($arr1 + $arr2);
it produces the output
Array
(
[0] => 1
[1] => 2
[2] => blue
)
which is probably not what you expect. The problem is that PHP tries to combine arrays and
dictionaries into a single concept, which doesnât quite work right as either.
Here is a proper array-concatenation function, which can take any number of array arguments:
function array_concat(...$arrays)
/* concatenates the items of a sequence of arrays. */
{
$result = array();
foreach ($arrays as $arr)
{
foreach ($arr as $elt)
{
$result[] = $elt;
} /*foreach*/
} /*foreach*/
return
$result;
} /*array_concat*/
The output from
print_r(array_concat($arr1, $arr2));
is the much more reasonable
Array
(
[0] => 1
[1] => 2
[2] => red
[3] => green
[4] => blue
)
----
Server IP: 208.43.231.9
Probable Submitter: 118.92.45.19
----
Manual Page -- http://php.net/manual/en/ref.array.php
Edit -- https://master.php.net/note/edit/122017
Del: integrated -- https://master.php.net/note/delete/122017/integrated
Del: useless -- https://master.php.net/note/delete/122017/useless
Del: bad code -- https://master.php.net/note/delete/122017/bad+code
Del: spam -- https://master.php.net/note/delete/122017/spam
Del: non-english -- https://master.php.net/note/delete/122017/non-english
Del: in docs -- https://master.php.net/note/delete/122017/in+docs
Del: other reasons-- https://master.php.net/note/delete/122017
Reject -- https://master.php.net/note/reject/122017
Search -- https://master.php.net/manage/user-notes.php