PHP in_array() Function

Definition

The in_array() function returns true if an array contains a specific value; otherwise, it will return false:

Syntax

PHP in_array() Function has the following syntax.

bool in_array ( mixed needle, array haystack [, bool strict] )

Parameter

ParameterIs RequiredDescription
searchRequired.What to search for
arrayRequired.Array to search
typeOptional.Use strict checking

The optional boolean third parameter for in_array() (set to false by default) defines whether to use strict checking.

If parameter three is set to true, PHP will the === operator to do the search.

Example 1

Is an element in an array


<?PHP//w w w . ja  va 2s . com
$needle = "java2s.com";
$haystack = array("A", "java2s.com", "B", "C", "D", "E");

if (in_array($needle, $haystack)) {
   print "$needle is in the array!\n";
} else {
   print "$needle is not in the array\n";
}
?>

The code above generates the following result.

Example 2

Use strict checking


<?PHP/*from w  w  w .  j a  v a 2 s .  c  o m*/
$needle = 5;
$haystack = array("5", "java2s.com", "B", "C", "D", "E");

if (in_array($needle, $haystack,true)) {
   print "$needle is in the array!\n";
} else {
   print "$needle is not in the array\n";
}

if (in_array($needle, $haystack,TRUE)) {
   print "$needle is in the array!\n";
} else {
   print "$needle is not in the array\n";
}
?>

The code above generates the following result.





















Home »
  PHP Tutorial »
    Function reference »




PHP Array Functions
PHP Calendar Functions
PHP Class Functions
PHP Data Type Functions
PHP Date Functions
PHP File Functions
PHP Image Functions
PHP Math Functions
PHP MySQLi Functions
PHP SimpleXML Functions
PHP String Functions
PHP XML Functions
PHP Zip Functions