1

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.

2
  • I guess the indices are different; Do a var_dump($result) to check. Commented Jul 22, 2013 at 12:22
  • use var_dump($result); to inspect the variable. Commented Jul 22, 2013 at 12:22

2 Answers 2

6

the intersection maintains index. do the following

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

Then you can access with $result[0];

Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.