user2588490
user2588490

Reputation: 41

Reindex array after filtering with array_intersect()

I want to find the intersection of elements between two arrays; the result will go to another array.

I've written: $result = array_intersect($arrayone,$arraytwo);

If I write count($result) it returns a correct value, but if I write $result[0] it returns the following notice: Notice: Undefined offset: 0.

Upvotes: 1

Views: 358

Answers (2)

Jon
Jon

Reputation: 437386

That is because array_intersect preserves the keys from its first argument. If $arrayone did not have a key 0, $result will also not have one.

If you are not interested in the keys of the result then you can simply reindex it with array_keys($result) and then access the elements given numeric indexes.

However, do keep in mind that directly referring to items inside an array with numeric indexes is somewhat unusual in PHP; in most cases there are more appropriate ways to handle numerically indexed arrays.

Upvotes: 4

DevZer0
DevZer0

Reputation: 13535

the intersection maintains index. do the following

$result = array_intersect($arrayone,$arraytwo);
$result = array_values($result);

Then you can access with $result[0];

Upvotes: 6

Related Questions