Finding a Given Value in an Array in PHP


How To Find a Specific Value in an Array in PHP?



There are two functions can be used to test if a value is defined in an array or not:

  • array_search($value, $array) - Returns the first key of the matching value in the array, if found. Otherwise, it returns false.
  • in_array($value, $array) - Returns true if the $value is defined in $array.

Here is a PHP script on how to use array_search():

$array = array("Perl", "PHP", "Java", "PHP");
print("Search 1: ".array_search("PHP",$array)."\n");
print("Search 2: ".array_search("Perl",$array)."\n");
print("Search 3: ".array_search("C#",$array)."\n");

This script will print:

Search 1: 1
Search 2: 0
Search 3:


Retrieving All Keys from an Array in PHP

Verifying If a Key Exists in an Array in PHP

PHP Built-in Functions for Arrays

⇑⇑ PHP Tutorials

2017-01-21, 1735🔥, 0💬