I'm getting these results in that order ...
array(2) { [0]=> int(1) [1]=> int(2) }
WARNING array_merge(): Argument #2 is not an array on line number 12
NULL
WARNING array_merge(): Argument #1 is not an array on line number 14
NULL
And I'm trying to understand why ..
Here is my code :
$referenceTable = array();
$referenceTable['val1'] = array(1, 2);
$referenceTable['val2'] = 3;
$referenceTable['val3'] = array(4, 5);
$testArray = array();
$testArray = array_merge($testArray, $referenceTable['val1']);
var_dump($testArray);
$testArray = array_merge($testArray, $referenceTable['val2']);
var_dump($testArray);
$testArray = array_merge($testArray, $referenceTable['val3']);
var_dump($testArray);
The issue here is that, if either the first or second argument to array_merge()
is not an array, the return value will be NULL
As a result, the call to $testArray = array_merge($testArray, $referenceTable['val2'])
evaluates to $testArray = array_merge($testArray, 3)
and, since 3
is not of type array
, this call to array_merge()
returns NULL
, which in turn ends up setting $testArray
equal to NULL
. Then, when we get to the next call to array_merge()
, $testArray
is now NULL
so array_merge()
again returns NULL
.
The fix for this is straightforward. If we simply typecast the second argument to an array, we will get the desired results. The corrected array_merge()
calls would therefore be as follows:
$testArray = array_merge($testArray, (array)$referenceTable['val1']);
var_dump($testArray);
$testArray = array_merge($testArray, (array)$referenceTable['val2']);
var_dump($testArray);
$testArray = array_merge($testArray, (array)$referenceTable['val3']);
var_dump($testArray);
which will yield the following output:
array(2) { [0]=> int(1) [1]=> int(2) }
array(3) { [0]=> int(1) [1]=> int(2) [2]=> int(3) }
array(5) { [0]=> int(1) [1]=> int(2) [2]=> int(3) [3]=> int(4) [4]=> int(5) }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.