PHP 5 Array search
Array search
In this section, we will learn how search an array element with the help of pre-defined function and without pre-defined function.
Array_search function
array_search function return the index of the element of the found element, otherwise return false.
Example array_search
<?php $z=array ( "Apple", "Banana", "Orange", "Grapes" ); echo array_search("Banana",$z); ?>
$z is an array variable that holds four elements and pass the string you want search into the array_search as the first argument, it will be given the index number of the element.
Note: Banana and banana are different strings.
Output
Search associative array
<?php $z=array ( "h"=>"Apple", "i"=>"Banana", "j"=>"Orange", "k"=>"Grapes" ); $x=array_search("Orange",$z); echo "Searched element found at :".$x; ?>
Output
Search array element without function
You can search array element without using any pre-defined function. Let us see the following example.
Search array element
<?php $y=array(12,10,5,15,20); $x=0; for($i=0;$i<count($y);$i++) { if($y[$i]==5) { $x=$i; break; } } if($x>=0) { echo "Found at "; echo $x+1 ." place"; } else { echo "Not found"; } ?>
$y is a simple array variable that hold some element, you can search an element with the help of if-else statement, as shown above.
Output
Search Associative array element
<?php $z=array("h"=>"Apple","i"=>"Banana","j"=>"Orange","k"=>"Grapes"); $x=0; foreach($z as $key=>$value) { if($z[$key]=="Banana") { $x=$key; break; } } if($x>=0) { echo "Found at "; echo $key ." th place"; } else { echo "not found"; } ?>
All the thing will be same as the indexed array except foreach loop at the place of for loop.