mesllo
mesllo

Reputation: 583

Notice: Array to string conversion PHP

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 )?

Upvotes: 0

Views: 2827

Answers (1)

Rizier123
Rizier123

Reputation: 59681

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 ) )

Upvotes: 3

Related Questions