Judgment method: 1. Remove duplicate values in the array, syntax "$newArr=array_unique($arr);"; 2. Get the length of the array after deduplication. If the array length is 1, then the original array The elements in are all the same, the syntax is "if(count($newArr)==1){//Operation when they are all the same}".
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
In php, you can use array_unique () and count() functions to determine whether the elements in the array are the same.
Implementation idea:
Use array_unique() to remove duplicate values in the array. If two or more array values are the same, only the first value is retained and the other values are removed.
Use count() to obtain the length of the array after deduplication
If the array length is 1, it means that there is only one element in the original array , that is, the elements in the original array are all the same
If the array length is not 1, it means that not all the elements in the original array are the same
Implementation method:
1. Use array_unique() to remove duplicate values in the array
<?php $arr1 = array(1,1,1,1,1,1,1); var_dump(array_unique($arr1)); $arr2 = array(1,2,1,3,1,1,1); var_dump(array_unique($arr2)); ?>
<?php header('content-type:text/html;charset=utf-8'); $arr = array(1,1,1,1,1,1,1); $newArr=array_unique($arr); if(count($newArr)==1){ echo "数组中元素都相同"; }else{ echo "数组中元素不是都相同"; } ?>
<?php header('content-type:text/html;charset=utf-8'); function f($arr){ $newArr=array_unique($arr); if(count($newArr)==1){ echo "数组中元素都相同<br>"; }else{ echo "数组中元素不是都相同<br>"; } } $arr1 = array(1,1,1,1,1,1,1); $arr2 = array(1,2,1,3,1,1,1); f($arr1); f($arr2) ?>
PHP Video Tutorial"
The above is the detailed content of How to determine whether the elements in an array are the same in php. For more information, please follow other related articles on the PHP Chinese website!