Linear Search in PHP

The following function searches for an item $search_item form an array $data_array by going through each items of the array. If item found in the $data_array array then it returns the index number of that item, otherwise it returns -1;

$data_array = [1,4,23,33,2,56,11,44,22,76,200,3];
$search_item = 11;
function linear_search( $data_array, $search_item ){
	for( $i = 0; $i < count($data_array); $i++ ){
		if( $data_array[$i] == $search_item ){
			return $i;
		}
	}
	return -1;
}

$itm_indx = linear_search( $data_array, $search_item ); 
if( $itm_indx > 0 ){
	echo 'item found in index = '.$itm_indx;
}else{
	echo 'item not found';
}

Leave a Reply

Your email address will not be published. Required fields are marked *