skull

Robert Tamayo

R
B
code
skull

Casting to Resolve PHP Array_Merge Warnings

PHP Warnings are annoying, but at least they don't break the page or stop the script. I learned something about Warnings and PHP's array_merge function today, and found an easy way to avoid them.

$array = ['list', 'of', 'words'];
$not_array = 3;
$merged = array_merge($array, $not_array);
var_dump($merged);

Running the above code will throw a Warning saying that the second argument was not an array. Also, although the Warning does not break the code, the value of $merged will be null, potentially causing issues down the line.

Here's how to fix that with casting:

$array = ['list', 'of', 'words'];
$not_array = 3;
$merged = array_merge((array) $array, (array) $not_array);
print_r($merged);

Because the parameters of array_merge are arrays, we can simply cast any argument passed to it as an array. PHP will figure out if something is already an array, and if it is not, it will make it into an array before passing it to the function. Whereas the output of the var_dump in the first example was NULL, the output of the print_r after adding the casting is now as expected:

Array
(
    [0] => list
    [1] => of
    [2] => words
    [3] => 3
)

Comments:
Leave a Comment
Submit