note 70762 added to language.operators.comparison
| From: | bishop at osu1 dot php dot net | Date: | Thu, 26 Oct 2006 22:49:53 +0000 |
| Subject: | note 70762 added to language.operators.comparison | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-119152@lists.php.net to get a copy of this message | ||
When you want to know if two arrays contain the same values, regardless of the values' order,
you cannot use "==" or "===". In other words:
<?php
(array(1,2) == array(2,1)) === false;
?>
To answer that question, use:
<?php
function array_equal($a, $b) {
return (is_array($a) && is_array($b) && array_diff($a, $b) === array_diff($b,
$a));
}
?>
A related, but more strict problem, is if you need to ensure that two arrays contain the same
key=>value pairs, regardless of the order of the pairs. In that case, use:
<?php
function array_identical($a, $b) {
return (is_array($a) && is_array($b) && array_diff_assoc($a, $b) ===
array_diff_assoc($b, $a));
}
?>
Example:
<?php
$a = array (2, 1);
$b = array (1, 2);
// true === array_equal($a, $b);
// false === array_identical($a, $b);
$a = array ('a' => 2, 'b' => 1);
$b = array ('b' => 1, 'a' => 2);
// true === array_identical($a, $b)
// true === array_equal($a, $b)
?>
(See also the solution "rshawiii at yahoo dot com" posted)
----
Server IP: 64.71.164.2
Probable Submitter: 24.148.147.65
----
Manual Page -- http://www.php.net/manual/en/language.operators.comparison.php
Edit -- https://master.php.net/note/edit/70762
Del: integrated -- https://master.php.net/note/delete/70762/integrated
Del: useless -- https://master.php.net/note/delete/70762/useless
Del: bad code -- https://master.php.net/note/delete/70762/bad+code
Del: spam -- https://master.php.net/note/delete/70762/spam
Del: non-english -- https://master.php.net/note/delete/70762/non-english
Del: in docs -- https://master.php.net/note/delete/70762/in+docs
Del: other reasons-- https://master.php.net/note/delete/70762
Reject -- https://master.php.net/note/reject/70762
Search -- https://master.php.net/manage/user-notes.php