0

Riht now I use array_merge_recursive but if one of my 3 arrays is null I get for echo json_encode($array4);

null

I have 3 arrays in my php file:

$array1 = json_decode($array1, TRUE);
$array2 = json_decode($array2, TRUE);
$array3 = json_decode($array3, TRUE);

If I echo each of the arrays:

echo json_encode($array1); = {"results":[{"cat_id":2,"cat_name":"bicycle repairs"}]}

echo json_encode($array2); = {"results":[{"cat_id":"4","cat_name":"plumber"},{"cat_id":"5","cat_name":"Electrician"},{"cat_id":"6","cat_name":"vet"}]}

echo json_encode($array3);= {"results":[{"cat_id":3,"cat_name":"Doctor"}]}

And then I merge these arrays together like this:

$array4 = array_merge_recursive($array1['results'], $array2['results'], $array3['results']);

Which would give me:

[{"cat_id":2,"cat_name":"bicycle repairs"},{"cat_id":"4","cat_name":"plumber"},{"cat_id":"5","cat_name":"Electrician"},{"cat_id":"6","cat_name":"vet"},{"cat_id":3,"cat_name":"Doctor"}]

But if any of $array1, $array2 or $array3 is null then $array4 doesn't work. How can I overcome this?

CHarris
  • 2,693
  • 8
  • 45
  • 71

2 Answers2

0

I'm afraid that the library only admits arrays as arguments (https://www.php.net/manual/en/function.array-merge-recursive.php).

So if you want merge all elements I advise you that use ?? (Null Coalescing operator) that return the first params if isset and is not null, you can do something like this:

array_merge_recursive($array1['results']??[], $array2['results']??[], $array3['results']??[])
kb05
  • 69
  • 4
0

I would make a helper function to check if you variable is an Array. If not just make it an empty one

function MakeArray($arr){
    if (!is_array($arr)) return [];
    return $arr;
}
$arr1 = MakeArray([1,2,4]);
$arr2 = MakeArray([5,6]);
$arr3 = MakeArray(NULL);

This way you can guarantee that it will work even if you pass, for example, a string

Carlos Alves Jorge
  • 1,919
  • 1
  • 13
  • 29