Searching for arrays in PHP can use sequential search or binary search. Among them, sequential search is relatively simple, which is to compare and search one by one. But the disadvantage is also obvious. If the element being searched happens to be at the last one, the number of loops will be too many.
Search the array one by one to confirm whether there is an element, and return the element if it exists location information. Flag information can be set, the initial value is false. Find the direct output location and set the flag to true. If the loop end flag is still false, it was not found.
<br/>
$arr =[123,19,38,29,10,34]; function search($arr,$target){ // 参数:目标数组 目标元素 foreach ($arr as $key => $value) { if($value == $target){ return $key.'<br>'; } } return false; }
Assume that the array is in strict ascending order. If the target element is larger than the middle value, the search range is reduced by half to the right. If the value of the target element is smaller than the value of the middle element, the search range is reduced by half to the left.
function half_search($arr,$target){ // 定义出初始的第一个,最后一个元素的下标范围 $len = count($arr); $left =0; $right =$len -1; // 循环查找 // 范围不断的移动 ,必须满足一个条件 // 最左侧元素的下标 小于等于右侧元素的下标 while($left <= $right){ // 中间元素的下标 $middle = floor(($left + $right) /2); // 目标元素与中间元素进行比较 if($target == $arr[$middle]){ return $middle; } // 如果目标元素小于中间元素 // 范围向左缩小一半 if($target < $arr[$middle]){ $right =$middle-1 ; } // 如果目标元素大于中间元素 // 范围向右缩小一半 if($target > $arr[$middle]){ $left = $middle + 1; } } // 循环终止了 // 没有找到 return false; }
Related recommendations:
PHP binary method to implement array search function tutorial
##php array Find key functions
php array search function summary
The above is the detailed content of PHP simple array search algorithm sharing. For more information, please follow other related articles on the PHP Chinese website!