Saturday, April 7, 2018

Errors when merging arrays in PHP

You can run code online here: http://www.writephponline.com/

At first, try this code:
$array;
$array2 = [1, 2, 3];
$array3 = array_merge($array, $array2);
print_r($array3);

You get an error saying "array_merge(): Argument #1 is not an array on line 3".
Why? It's because arguments of array_merge can not be null. So, for example,
$array = CustomerEntity.getCustomersWithAppointment();
$array2 = [1, 2, 3];
$array3 = array_merge($array, $array2);
print_r($array3);
this works as long as CustomerEntity.getCustomersWithAppointment() returns array value, but doesn't work when it returns null.

To avoid this problem, parse the arguments to array.
$array;
$array2 = [1, 2, 3];
$array3 = array_merge((array)$array, $array2);
print_r($array3);

Or check if the arguments are array.
$array;
$array2 = [1, 2, 3];
if(is_array($array)){
    $array3 = array_merge($array, $array2);
}else{
    $array3 = $array2;
}
print_r($array3);