PHP Array Search


 

PHP Array Search

PHP Array Search: In this tutorial you will come to know about the array_search(),In PHP, array_search() function performs a search for a value in an array, in this tutorial we will have several examples which would exemplify this concept.

PHP Array Search: In this tutorial you will come to know about the array_search(),In PHP, array_search() function performs a search for a value in an array, in this tutorial we will have several examples which would exemplify this concept.

PHP Array Search

In PHP, array_search() function performs a search  for a value in an array, as with in_array(). If the value is found then the index position of that key (which could be string or number) will be returned.

General Format mixed array_search ( mixed $search , array $array [, bool $strict ] )
Parameters $search: The value to be searched $array: The array in which the value to be searched $strict: If the value is set to true then the types of $search and $array will be checked
Return Value Return the key for $search if it is found in $array, otherwise false

 

Example 1:

<?php

$array=array("new"=>11,"delhi"=>12,"common" => 13,"wealth"=>14,"game"=>15);

echo"<br/><b>Initially the values of \$array is:</b><br/>";

var_dump($array);

$key=13;

echo"<br/><b>Now we will search $key in \$array</b><br/>";

$search=array_search($key,$array);

echo"<br/><b>$key is found at $search</b><br/>";

?>

Output:

Initially the values of $array is:
array(5) {
  ["new"]=>
  int(11)
  ["delhi"]=>
  int(12)
  ["common"]=>
  int(13)
  ["wealth"]=>
  int(14)
  ["game"]=>
  int(15)
}

Now we will search 13 in $array

13 is found at common


Example 2:

<?php

$array=array("new"=>11,"delhi"=>12,"common","wealth"=>14,"game"=>15);

echo"<br/><b>Initially the values of \$array is:</b><br/>";

var_dump($array);

$key="common";

echo"<br/><b>Now we will search \"$key\" in \$array</b><br/>";

$search=array_search($key,$array);

echo"<br/><b>$key is found at $search</b><br/>";

?>

Output:

Initially the values of $array is:
array(5) {
  ["new"]=>
  int(11)
  ["delhi"]=>
  int(12)
  [0]=>
  string(6) "common"
  ["wealth"]=>
  int(14)
  ["game"]=>
  int(15)
}

Now we will search "common" in $array

common is found at 0

 

Ads