Ray
Ray

Reputation: 51

How to find matching values in multidimentional arrays in PHP

I am wondering if anyone could possibly help?....I am trying to find the matching values in two multidimensional arrays (if any) and also return a boolean if matches exist or not. I got this working with 1D arrays, but I keep getting an array to string conversion error for $result = array_intersect($array1, $array2); and echo "$result [0]"; when I try it with 2d arrays.

// matching values in two 2d arrays?
$array1 = array (array ('A8'), array (9,6,3,4));
$array2 = array (array ('A14'), array (9, 6, 7,8));


    $result = array_intersect($array1, $array2);

       if ($result){
       $match = true;
       echo "$result [0]";

       }
       else{
       $match = false;
       }

    if ($match === true){
        //Do something
    }
    else {
        //do something else

    }

Upvotes: 1

Views: 78

Answers (2)

Don't Panic
Don't Panic

Reputation: 41810

The PHP documentation for array_intersect states:

Note: Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation is the same.

So, the array to string conversion notice is occurring when PHP attempts to compare the array elements. In spite of the notice, PHP will actually convert each of the sub-arrays to a string. It is the string "Array". This means that because

array_intersect() returns an array containing all the values of array1 that are present in all the arguments.

you will end up with a $result containing every element in $array1, and a lot of notices.

How to fix this depends on exactly where/how you want to find matches.

If you just want to match any value anywhere in either of the arrays, you can just flatten them both into 1D arrays, and compare those with array_intersect.

array_walk_recursive($array1, function ($val) use (&$flat1) {
    $flat1[] = $val;
});
array_walk_recursive($array2, function ($val) use (&$flat2) {
    $flat2[] = $val;
});

$result = array_intersect($flat1, $flat2);

If the location of the matches in the arrays is important, the comparison will obviously need be more complex.

Upvotes: 1

Frank Li
Frank Li

Reputation: 31

This error(PHP error: Array to string conversion) was caused by array_intersect($array1, $array2), cause this function will compare every single element of the two arrays.

In your situation, it will consider the comparison as this: (string)array ('A8') == (string)array ('A14'). But there isn't toString() method in array, so it will incur the error.

So, if you want to find the matching values in two multidimensional arrays, you must define your own function to find it.

Upvotes: 0

Related Questions