PHP determines whether the same number exists in two ordered arrays Sample code analysis
<?php $len1 = sizeof($arr1); $len2 = sizeof($arr2); $flag = false; //用来退出外层循环 $start = 0; $counter = 0; for($i = 0; $i < $len1; $i++) { if($flag) { break; } // $start 记录上次循环到的索引 for($j = $start; $j < $len2; $j++) { if($arr2[$j] == $arr1[$i]) { echo 'find, ', $arr2[$j]; $flag = true; break; } // 用 $counter 来控制次数,当前内循环中仅记录一次 if($arr2[$j] > $arr1[$i] && $counter == 0) { $start = $j; $counter++; } } $counter = 0; //下一次循环开始,重置为0 }
Method 2:
Idea: First set two subscripts, initialize them to the starting addresses of the two arrays, and advance forward in sequence. The rule of advancement is to compare the numbers in the two arrays. The subscript of the smaller array is pushed forward one step further until the subscript of any array reaches the end of the array. If the same number has not been encountered at this time, it means that the subscript in the array is There are no identical numbers.
<?php $i = $j = 0; $len1 = count($arr1); $len2 = count($arr2); while($i < $len1 && $j < $len2) { if($arr1[$i] == $arr2[$j]) { echo 'find, ', $arr1[$i]; break; } if($arr1[$i] > $arr2[$j]) { $j ++; } else { $i ++; } }
The above is the detailed content of PHP determines whether the same number exists in two ordered arrays sample code analysis. For more information, please follow other related articles on the PHP Chinese website!