$nums = [1, 2, 3, 4, 5, 6]; $num=5; $start = 0; $end = count($nums)-1; echo binary_search($nums,$num,$start,$end); function binary_search($nums,$num,$start,$end){ $mid = floor(($start+$end)/2); $midNum = $nums[$mid]; if($num < $midNum){ $end = $mid-1; return binary_search($nums,$num,$start,$end); }elseif($num > $midNum){ $start = $mid+1; return binary_search($nums,$num,$start,$end); }elseif($midNum == $num){ return $mid; } }