Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP array_merge if not empty

Trying to merge 4 arrays, but some may be empty at certain times.

$array_1 = array('something1', something2);
$array_2 = array('something3', something4);
$array_3 = array();
$array_4 = array('something1', something2);

$list = array_merge($array_1,$array_2,$array_3,$array_4);

print_r($list);

But if one of the arrays are empty, there will be an error. I've been googling forever, but I can't find a solid simple answer on how to check for empty arrays before merging.

Argument #2 is not an array

Or whichever array is empty is the argument number. How do I strip out empty arrays before merging?

like image 587
David Avatar asked Nov 21 '13 21:11

David


People also ask

How can I merge two arrays in PHP without duplicates?

You can use the PHP array_unique() function and PHP array_merge() function together to merge two arrays into one array without duplicate values in PHP.

What is the best method to merge two PHP objects?

Approach 1: Convert object into data array and merge them using array_merge() function and convert this merged array back into object of class stdClass. Note: While merging the objects using array_merge(), elements of array in argument1 are overwritten by elements of array in argument2.


1 Answers

There is NO error with an empty array. There is only an error if the arg is NOT an array.

You could check is_array() or:

$list = array_merge(
(array)$array_1,
(array)$array_2,
(array)$array_3,
(array)$array_4
);
like image 166
AbraCadaver Avatar answered Sep 28 '22 08:09

AbraCadaver