How To Find a Specific Value in an Array

Q

How To Find a Specific Value in an Array? - PHP Script Tips - PHP Built-in Functions for Arrays

✍: FYIcenter.com

A

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 arrary_search():

<?php 
$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");
print("\n");
?>

This script will print:

Search 1: 1
Search 2: 0
Search 3:

2007-04-20, 5065👍, 0💬