NYCPHP Meetup

NYPHP.org

[nycphp-talk] what's up with array_diff()

Ivan Kedrin ikedrin at clinicaladvisors.com
Wed Sep 19 23:39:00 EDT 2007


take a look at http://us.php.net/operators.comparison for some suggestions:

 

function array_equal($a, $b) {
    return (is_array($a) && is_array($b) && array_diff($a, $b) ===
array_diff($b, $a));
}

 

function array_identical($a, $b) {
    return (is_array($a) && is_array($b) && array_diff_assoc($a, $b) ===
array_diff_assoc($b, $a));
}

 

alternatively, you could always serialize() and compare using == if your
definition of "equals" requires them to be identical in every respect
including order of the keys and if you don't care about overhead related to
serialization. there are probably also some shortcuts that could save some
cpu cycles but it depends on the type of data you got in your arrays, array
size, etc. 

 

-ivan kedrin

 

  _____  

From: talk-bounces at lists.nyphp.org [mailto:talk-bounces at lists.nyphp.org] On
Behalf Of David Mintz
Sent: Wednesday, September 19, 2007 4:35 PM
To: NYPHP Talk
Subject: [nycphp-talk] what's up with array_diff()

 


The description of array_diff at
http://www.php.net/manual/en/function.array-diff.php says it computes the
difference between the arrays you pass it, and returns that difference as an
array. 

The behavior is that it finds and returns an array of elements that are
present in the first argument that are not present in the following
arguments, so the order in which you pass in your arrays is all-important. 

I am trying to find out if two arrays are different from each other or not.
I can sort() and then compare with ==, but I thought this might be more
elegant.

Now I am looking at 

       if (array_diff($one,$two) or array_diff($two,$one)) { 
           /* do something */ 
       }

but I wonder if anyone can suggest a better way.

Thanks.

-- 
David Mintz
http://davidmintz.org/

The subtle source is clear and bright 
The tributary streams flow through the darkness 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.nyphp.org/pipermail/talk/attachments/20070919/a9332886/attachment.html>


More information about the talk mailing list