Home >Backend Development >PHP Tutorial >How to determine array equality in PHP and introduction to array operators_PHP Tutorial

How to determine array equality in PHP and introduction to array operators_PHP Tutorial

WBOY
WBOYOriginal
2016-07-13 09:59:001077browse

The method of judging array equality in php and the introduction of array operators

This article mainly introduces the method of judging array equality in php and the introduction of array operators. This article explains the relevant Knowledge and example code are given, friends in need can refer to it

How to determine if two arrays are equal? It’s actually very simple, just use == or ===
The description in the php manual is as follows:

php中判断数组相等的方法以及数组运算符介绍   帮客之家

Can multi-dimensional arrays like array('k'=>array()) be equal using the above method? Of course you can.
If the array is numerically indexed, you need to pay attention, see the code:

The code is as follows:


$a = array("apple", "banana");
$b = array(1 => "banana", "0" => "apple");

var_dump($a == $b); // bool(true)
var_dump($a === $b); // bool(false)
?>

In addition to the array operator ==, there are other more convoluted methods to judge. For example, use array_diff($a, $b) to compare the difference sets of two arrays. If the difference sets are empty arrays, they are equal.
Then let’s talk about the plus operator of arrays. The difference with array_merge is that when equal keys are encountered, when using , the left array will overwrite the value of the right array. On the contrary, with array_merge, the later array will overwrite the previous one.

The code is as follows:


$a = array("a" => "apple", "b" => "banana");
$b = array("a" => "pear", "b" => "strawberry", "c" => "cherry");

$c = $a $b; // Union of $a and $b
echo "Union of $a and $b: n";
var_dump($c);

$c = array_merge($a, $b); // Union of $b and $a
echo "array_merge of $b and $a: n";
var_dump($c);
?>

Output after execution:

The code is as follows:


Union of $a and $b:
array(3) {
["a"]=>
string(5) "apple"
["b"]=>
string(6) "banana"
["c"]=>
string(6) "cherry"
}
array_merge of $b and $a:
array(3) {
["a"]=>
string(4) "pear"
["b"]=>
string(10) "strawberry"
["c"]=>
string(6) "cherry"
}

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/976536.htmlTechArticleHow to determine array equality in PHP and introduction to array operators. This article mainly introduces how to determine array equality in PHP. Methods and array operators are introduced. This article explains the relevant knowledge and gives...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn