PHP array_diff to determine the difference of the array

 The PHP array_diff function can be used to determine the differences between PHP arrays and return a new array containing the key values ​​of the difference array, so at least two different PHP Arrays must be put in the PHP array_diff function to make sense. The array_diff function is a built-in function of PHP and can be used without additional installation. Both PHP version 4.0.1 and PHP 5 can be used.


Basic syntax of PHP array_diff function

array array_diff( $array1 , $array2 , $array3 , ... )


At least two PHP Arrays must be included in the grammar. More arrays can be added later to perform multi-array comparison. It is worth noting that each array is compared with the first array, so the value returned by array_diff is a new one. The new array value includes all the values ​​that appear in $array1 but do not appear in other arrays, and the key names will be retained.

PHP array_diff function example reference
<?php
 $Array1=array('A','B','C','D');
 $Array2=array('C','D','E','F');
 $Array3=array('A','B','E','F');
 $NewArray1=array_diff($Array1,$Array2);
 print_r($NewArray1);
 $NewArray2=array_diff($Array1,$Array3);
 print_r($NewArray2);
?>
The above output results as in the



example. At the beginning, three different arrays are prepared, namely $Array1, $Array2 and $Array3. Then use the array_diff function to compare the two arrays $Array2 and $Array3 with the first $Array1. What is the difference? The function of print_r is to output the array. It is not difficult to see that there are two different key values ​​of A and B in the first array returned, and the two key values ​​of C and D in the second array returned. , And the key names of C and D still maintain the key names in $Array1, which is the characteristic of the PHP array_diff function.

Post a Comment

0 Comments