0

In my company's code I stumbled about the following use-case of in_array(): (replica of what happens)

$theHystack = [
    'id' => 3,
    'location' => 'Berlin'
];

$theNeedle = [
    'id' => 3,
    'location' => 'Berlin'
];

echo in_array($theNeedle, $theHystack, true)  
    ? 'true' 
    : 'false';

The documentation of in_array states that $needle can be of type mixed therefore it might be possible that this works.

To be certain I started to play around with the shown code however the result was always the same.

All results were false

The scenario was actually !in_array() thus it should return always true.

Question:

Is there a way of creating such a validation where you could validate an associative array with another associative array?

I'm looking for build-in php functions that could do something.

Beru
  • 657
  • 1
  • 6
  • 21
  • Possible duplicate of [How to use PHP in\_array with associative array?](https://stackoverflow.com/questions/21809116/how-to-use-php-in-array-with-associative-array) – treyBake Jul 25 '19 at 11:46
  • Are you checking they're identical? In which case `===`, or just that the full array exists in another, in which case making use of array_diff / array_intersect may help. – Jonnix Jul 25 '19 at 11:47
  • @treyBake notice OP last row `I'm looking for build-in php functions that could do something.` – MorganFreeFarm Jul 25 '19 at 11:47
  • 1
    @MorganFreeFarm but, if there isn't anything built-in (which I'm not sure there is), then the functionality has to be built, in which case, check linked dupe :) – treyBake Jul 25 '19 at 11:49
  • @Jonnix If they're identical. – Beru Jul 25 '19 at 11:50
  • @GentleSama Then just `$arrayOne === $arrayTwo`? – Jonnix Jul 25 '19 at 11:50
  • No, it's a poor example, I imagine usually there would be more than one entry in one or both arrays. – droopsnoot Jul 25 '19 at 11:51
  • @Jonnix Haven't thought about that and it works! :) – Beru Jul 25 '19 at 11:53
  • 2
    Your code works in the haystack is an array of arrays of the same format as the needle - so add another layer of `[]` round `$theHystack` and it will display true. – Nigel Ren Jul 25 '19 at 11:54
  • I add `[]` round `$theHystack` and `in_array` works fine. Can you add an example where `in_array` doesn't work? Here my code https://3v4l.org/ajjBa – potiev Jul 25 '19 at 14:18

0 Answers0