Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
468 views
in Technique[技术] by (71.8m points)

comparing arrays in php, without caring for the order

I have two arrays, $a and $b here, and need to check if they contain exactly the same elements (independently of the order). I am thinking of using

if (sizeof($a)==sizeof($b) AND array_diff($a,$b)==array())
{

}

But I am new to PHP, so I wonder: Is there a better way?

Since I need to use them as sets, maybe I should not use arrays at all but something else.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Well, we can do something like this:

if (count(array_diff(array_merge($a, $b), array_intersect($a, $b))) === 0) {
    //they are the same!
}

The reason it works, is that array_merge will make a big array that has all the elements of both $a and $b (all the elements that are in either $a, $b, or both). array_intersect will create an array that has all the elements that are in both $a and $b only. So if they are different,, there must be at least one element that does not appear in both arrays...

Also note that sizeof is not an actual function/construct, it's an alias. I'd suggest using count() for clarity...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...