Home > Backend Development > PHP Tutorial > Detailed explanation of how to determine whether all arrays are the same in PHP

Detailed explanation of how to determine whether all arrays are the same in PHP

WBOY
Release: 2016-07-25 08:52:43
Original
1628 people have browsed it
  1. //Forge an array with 100000 array elements, the first array element is 1, and the following 99999 are all 0
  2. for($i=0;$i<100000;$i++){
  3. if ($i==1)
  4. array_push($array,1);
  5. else
  6. array_push($array,0);
  7. }
  8. //The first loop method
  9. $len=count($array);
  10. for ($i=0; $i <$len ; $i++) {
  11. if($array[$i]!=$array[$i+1]){
  12. break;
  13. }
  14. }
  15. // Time consuming: Processed in 0.144372 second(s).
Copy code

Use array_count_values() in php to complete

  1. if(count(array_count_values($array))!=1){
  2. echo "Use the trick method in php to run: push";
  3. }
  4. //Processed in 0.133642 second(s).
Copy code

Because the first one of the constructed array is 1, and the next 99999 are all 0, construct an array again with the first 99999 being 1, and the last one being 0, as a comparison of the most and least times of a loop, and then Look at the running time of both: At this time,

//Time spent using the loop method: Processed in 0.211106 second(s). //Time spent using the array_count_values ​​method: Processed in 0.135076 second(s). When only one judgment is required, the time taken by the two methods is almost the same, but array_count_values ​​is still faster. But when we perform the most comparisons and put the different array elements at the end of the array, the latter takes almost half the time of the former.

array_count_values() What is the function: PHP has a built-in array_count_values() method in C language. This method is used to determine the number of occurrences of each array element. For example, if the array elements are 1, 1, 2, then it returns: Print the result: array(2) { [1]=> int(2) [2]=> int(1) } 1 appears twice and 2 appears once. At this time, determine how many elements there are in the array. If it is not 1, then there must be the same one.

Use more built-in methods. Regardless of the language, the writing methods of experts are generally more efficient. Of course, there may be exceptions. When writing programs in PHP, I still feel that built-in functions are more efficient.



source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template