1

I want to intersect array, the result will go to another array.
So I've written: $result = array_intersect($arrayone,$arraytwo);.

If I make count($result) it returns a correct value, but if I make $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.
    – jgroenen
    Jul 22, 2013 at 12:22
  • use var_dump($result); to inspect the variable. 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];

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.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.