Jump to content

Recommended Posts

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 by NotionCommotion

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.

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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.