0

I am finding the intersection between two arrays $item and $query respectively:

Array ( [0] => twitter [1] => 1 [2] => 561522539340771328 [3] => Array ( ) )

Array ( [0] => dig [1] => twitter )

This is the code I have:

if (array_intersect ( $query, $item )) {
            $intersection [] = $item;
}

Somehow it's returning the notice as defined on the title of this question. Either I'm too tired to notice what's wrong or I may be going mad, shouldn't it return Array ( [0] => twitter )?

3
  • 4
    This is because of your empty array at the end of your first array, remove it and it should work fine, does that do the trick for you or can't you change the array? (BTW: Now you just asign the $item array to $intersection, but i think you want to assign the output of array_intersect to a variable which you then can use) Commented Feb 5, 2015 at 22:02
  • Well technically, I can't remove it as that array may contain a list of extracted locations, however I'll just modify it to be set to 0 if no locations are found. Thank you! Actually the $item assignment in $intersection is intended! Commented Feb 5, 2015 at 22:25
  • Wrote a answer, If you have a multidimensional array you can use array_uintersect() to compare the values. Commented Feb 5, 2015 at 22:32

1 Answer 1

3

This is because you have an empty array at the end of your first array and array_intersect() is going to try to convert it to a string which gives you this error.

But to get rid of this error you can use array_filter() like this:

(Also you want to assign the output of array_intersect and then use this)

<?php       

    $item = array("twitter", 1, 561522539340771328, array());
    $query = array("dig", "twitter");

    if ($intersect = array_intersect($query, array_filter($item))) {
                                           //^^^^^^^^^^^^ See here
        $intersection [] = $intersect;
    }

    print_r($intersection);

?>

Output:

Array ( [0] => Array ( [1] => twitter ) )
Sign up to request clarification or add additional context in comments.

1 Comment

I tried this but it still would not work as the array wouldn't always be empty since it may contain locations sometimes. I was not aware that it was due to the final element being an array though so thanks. I've found a solution, posting shortly!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.