NotionCommotion Posted October 14, 2016 Share Posted October 14, 2016 (edited) I didn't expect the following to work, but then tried it and it does. Any gotchas I need to look out for? <?php $haystack=[ (object)['a'=>1,'b'=>1,'c'=>1], (object)['a'=>1,'b'=>2,'c'=>1], (object)['a'=>2,'b'=>1,'c'=>2], (object)['a'=>2,'b'=>2,'c'=>1], (object)['a'=>2,'b'=>2,'c'=>2], ]; var_dump(in_array((object)['a'=>2,'b'=>2,'c'=>1],$haystack)); //True var_dump(in_array((object)['a'=>1,'b'=>1,'c'=>2],$haystack)); //False var_dump(in_array((object)['b'=>2,'a'=>2,'c'=>1],$haystack)); //True Edited October 14, 2016 by NotionCommotion Quote Link to comment https://forums.phpfreaks.com/topic/302331-checking-if-array-exists-in-another-array/ Share on other sites More sharing options...
kicken Posted October 14, 2016 Share Posted October 14, 2016 Unless you perform a strict comparison (third parameter set to true) then PHP compares objects by checking each value. Comparing Objects When using the comparison operator (==), object variables are compared in a simple manner, namely: Two object instances are equal if they have the same attributes and values (values are compared with ==), and are instances of the same class. In your cases all objects are instances of stdClass so they meet the same class requirement. After that it checks each key/value to see if they match. If you set the third parameter of in_array to true so it does a strict check then all three cases would be false because every value is it's own unique instance even if all the keys are the same. Array's work similarly for a comparison so it would also work even if you had not cast them to objects first. Quote Link to comment https://forums.phpfreaks.com/topic/302331-checking-if-array-exists-in-another-array/#findComment-1538288 Share on other sites More sharing options...
NotionCommotion Posted October 14, 2016 Author Share Posted October 14, 2016 Thanks Kicken, Yes, I had first tried this as arrays, and saw that it also worked. What more surprised me was that ['a'=>1,'b'=>1,'c'=>2] and ['b'=>2,'a'=>2,'c'=>1] produced the same results. I guess I expected that PHP would interpret them as their string equivalent. Quote Link to comment https://forums.phpfreaks.com/topic/302331-checking-if-array-exists-in-another-array/#findComment-1538291 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.