EN VI

php check if value exist on all multidimensional arrays?

2024-03-15 05:00:07
How to php check if value exist on all multidimensional arrays

Currently going crazy on how to do this, basicly I have a multidimensional array and need a code to check all values and if value exists in all arrays than to return the result.

Parents visitPoints,islands,animals will always exist, although some times empty, the second level columns are dynamic so keys 20,35,57 change and there content.

$array = [
    'visitPoints'=>[
        20=>[2,5,6,8,10,11],
        35=>[2,5,6],
        57=>[1],
    ],
    'islands'=>[
        20=>[5,10,11],
        35=>[5,6]
    ],
    'animals'=>[
        20=>[5,11],
        35=>[]
    ]
];

And the result I'm looking for is this:

$result = [
    20=>[5,11],
    35=>[],
    57=>[]
];

was playing around with call_user_func_array('array_intersect', $array) but could not get the result I'm looking for.

Here is the sample link: https://3v4l.org/meX5p

Solution:

Isolate the first subset and apply it to the result, then iterate the remaining subsets by following the result array's keys and filter the respective rows with array_intersect() falling back to an empty array when a result row is not found for a respective key. (Demo)

$result = array_shift($array);
foreach ($array as $rows) {
    foreach ($result as $k => $row) {
        $result[$k] = array_values(array_intersect($result[$k], $rows[$k] ?? []));
    }
}
var_export($result ?? []);

I'll include null coalescing on the result in case the input array is empty.

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login