PHP Tutorial - 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/*from ww w. ja  va2s .  c  o m*/
$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/* www.  j  av  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.

Example 3

The following code shows how to check if a number is in an array.


// w  ww .j a v a 2s.com
<?php
   $primes = array(2,3,5,7,11,13,17,19,23,29,31,37,41,43,47);
   for($count = 1; $count++; $count < 1000) {
      $randomNumber = rand(1,50);
      if (in_array($randomNumber,$primes)) {
         break;
      } else {
         echo "<p>Non-prime number encountered: $randomNumber</p>";
      }
   }
?>