$arr = array();
$arr['val1'] = array(1, 2);
$arr['val2'] = 3;
$arr['val3'] = array(4, 5);
$arr2 = array();
$arr2 = array_merge($arr2, $arr['val1']);
var_dump($arr2);
$arr2 = array_merge($arr2, $arr['val2']);
var_dump($arr2);
$arr2 = array_merge($arr2, $arr['val3']);
var_dump($arr2);
There’s a problem with this code. It lies in the fact that array_merge will output a null if you give it anything but an array.
$arr['val2']
does not contain an array. Therefore when you merge it, the result will be null, and then the third merge will also result in null because it cascades down from the previous merge in the $arr2
variable.
How do we fix this? Simply typecast the second argument to an array, and you cover any case where the value is not an array:
$arr2 = array_merge($arr2, (array) $arr['val1']);
var_dump($arr2);
$arr2 = array_merge($arr2, (array) $arr['val2']);
var_dump($arr2);
$arr2 = array_merge($arr2, (array) $arr['val3']);
var_dump($arr2);
Testing your knowledge of array_merge