PHP array_search: finding a value in an array

- . PHP array_search(). , , , .

array_search() PHP :

mixed array_search (mixed value, array $collection [, bool strict])
      
      



:

  • $collection - , ;
  • value - ;
  • strict - , .

PHP array_search() value collection. , . , strict TRUE. .

, , . , .

, FALSE.

(===). , , FALSE, , 0 .

PHP programming language




1. PHP array_search() , .





<?php
$array = array(
 "season1" => "winter",
 "season2" => "spring",
 "season3" => "summer",
 "season4" => "autumn"
);
$result1 = array_search("winter", $array);
$result2 = array_search("summer", $array);
$result3 = array_search("april", $array);
?>
      
      



$result1 "season1", $result2 "season3", $result3 FALSE, "april" .

2. PHP array_search() , .

<?php
$array = array("", "", "", "", "", "", "");
$result = array_search("", $array);
?>
      
      



$result 1, "" $array.

3. .

<?php
$presidents = array(
 0 => "Washington",
 1 => "Adams",
 2 => "Jefferson",
 3 => "Madison",
 4 => "Monroe"
);
$result = array_search("Washington", $presidents);
if (!$result) {
 echo "G. Washington was not the first president of the USA";
}
?>
      
      



, , , .

George Washington - First President of the United States




Example 4. Only the key of the first match found is returned.

<?php
$song = ["jingle", "bells", "jingle", "bells", "jingle", "all", "the", "way];
$result = array_search("jingle", $song);
echo $result;
?>
      
      



Despite the fact that the desired value occurs three times in the array, the function will return only the first result found - 0. To search for multiple matches, it is recommended to use the PHP function array_keys ().




All Articles