search for in the  
<extractkey>
Last updated: Thu, 19 May 2005

in_array

(PHP 4, PHP 5)

in_array -- Checks if a value exists in an array

Description

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

Searches haystack for needle and returns TRUE if it is found in the array, FALSE otherwise.

If the third parameter strict is set to TRUE then the in_array() function will also check the types of the needle in the haystack.

Note: If needle is a string, the comparison is done in a case-sensitive manner.

Note: In PHP versions before 4.2.0 needle was not allowed to be an array.

Example 1. in_array() example

<?php
$os
= array("Mac", "NT", "Irix", "Linux");
if (
in_array("Irix", $os)) {
   echo
"Got Irix";
}
if (
in_array("mac", $os)) {
   echo
"Got mac";
}
?>

The second condition fails because in_array() is case-sensitive, so the program above will display:

Got Irix

Example 2. in_array() with strict example

<?php
$a
= array('1.10', 12.4, 1.13);

if (
in_array('12.4', $a, true)) {
   echo
"'12.4' found with strict check\n";
}

if (
in_array(1.13, $a, true)) {
   echo
"1.13 found with strict check\n";
}
?>

The above example will output:

1.13 found with strict check

Example 3. in_array() with an array as needle

<?php
$a
= array(array('p', 'h'), array('p', 'r'), 'o');

if (
in_array(array('p', 'h'), $a)) {
   echo
"'ph' was found\n";
}

if (
in_array(array('f', 'i'), $a)) {
   echo
"'fi' was found\n";
}

if (
in_array('o', $a)) {
   echo
"'o' was found\n";
}
?>

The above example will output:

'ph' was found
  'o' was found

See also array_search(), array_key_exists(), and isset().



User Contributed Notes
in_array
19-May-2005 09:12
Note that most array searching functions patterned (needle, haystack) and string searching functions are patterned (haystack, needle).
greg at serberus dot co dot uk
17-May-2005 07:49
Further to my previous post this may prove to be more efficient by eliminating the need for array_flip() on each iteration.

$distinct_words = array();

foreach ($article as $word) {

  if (!isset($distinct_words[$word]))
     $distinct_words[$word] = count($distinct_words);

}

$distinct_words = array_flip($distinct_words);
greg at serberus dot co dot uk
13-May-2005 09:50
in_array() doesn't seem to scale very well when the array you are searching becomes large. I often need to use in_array() when building an array of distinct values. The code below seems to scale better (even with the array_flip):

$distinct_words = array();

foreach ($article as $word) {

  $flipped = array_flip($distinct_words);

  if (!isset($flipped[$word]))
     $distinct_words[] = $word;

}

This only works with arrays that have unique values.
08-Mar-2005 08:15
I'd have to disagree with the previous poster.  The behavior is not "completely as expected."  If I do not know what data is in an array, and I search for the value "123abc", I certainly don't expect it to match the integer 123.  I expect it to match the string "123abc," period.  The needle should not be converted for the sake of comparison!  In the case of a string in the haystack or needle, the other value should be converted to a string before comparison.  This guarantees only equivalent values will be matched.

This kind of behavior is the reason I always use === in PHP instead of ==.  Too many things match otherwise.  Luckily, the "strict" option here gives the right results.

-Dan
Chris
07-Mar-2005 04:02
I hope everyone sees that the previous poster's comments are incorrect, in that the behavior is not ridiculous but completely as expected.

> in_array('123abc', array(123)) returns true
A string is being compared to an integer, in such a situation PHP assumes an integer context wherein '123abc' evaluates to the integer 123, thus a match.

> in_array('123abc', array('123')) returns false
A string is being compared to a string and OBVIOUSLY these strings are not equal.
22-Dec-2004 04:51
Please note this very ridiculous behaviour:

in_array('123abc', array(123)) returns true

in_array('123abc', array('123')) returns false

I guess this is because it is converting '123abc' to an int.
memandeemail at gmail dot com
17-Nov-2004 09:55
Some very helpfuly variant's, of functions:

class shared {
   /**lordfarquaad at notredomaine dot net 09-Sep-2004 11:44
   * @return bool
   * @param mixed $needle
   * @param mixed $haystack
   * @desc This function will be faster, as it doesn't compare all elements, it stops when it founds the good one. It also works if $haystack is not an array :-)
   */

   function in_array_multi($needle, $haystack)
   {
       if(!is_array($haystack)) return $needle == $haystack;
       foreach($haystack as $value) if(shared::in_array_multi($needle, $value)) return true;
       return false;
   }

   /**lordfarquaad function's variant1
   * @return bool
   * @param string $needle_key
   * @param mixed $haystack
   * @desc Search a key in the array and return if founded or not.
   */

   function in_array_key_multi($needle_key, $haystack)
   {
       if(!is_array($haystack)) return $needle_key == $haystack;
       foreach($haystack as $key => $value)
       {
           $value; // TODO: Extract the $key without seting $value
           if(shared::in_array_key_multi($needle_key, $key)) return true;
       }
       return false;
   }

   /**lordfarquaad function's variant2
   * @return bool
   * @param string $needlekey
   * @param mixed $needlevalue
   * @param mixed[optional] $haystack_array
   * @param string[optional] $haystack_key
   * @param mixed[optional] $haystack_value
   * @desc Search in array for the key and value equal.
   */
   function in_array_multi_and_key($needlekey, $needlevalue, $haystack_array = null, $haystack_key = null, $haystack_value = null)
   {
       if (!is_array($haystack_array)) return ($needlekey == $haystack_key and $needlevalue == $haystack_value);
       foreach ($haystack_array as $key => $value) if (shared::in_array_multi_and_key($needlekey, $needlevalue, $value, $key, $value)) return true;
       return false;
   }
}

HOW TO USE:

shared::in_array_multi(......)

it's very simple.
langewisch at lakoma dot com
04-Nov-2004 04:13
Hi,

if you want to search a value in a mutidimensional array try this.

Cu
Christoph

-------------------------------
<?
function in_multi_array($search_str, $multi_array)
{
   if(!
is_array($multi_array))
       return
0;
   if(
in_array($search_str, $multi_array))
       return
1;   
  
   foreach(
$multi_array as $key => $value)
   {
       if(
is_array($value))
       {
          
$found = in_multi_array($search_str, $value);
           if(
$found)
               return
1;
          
       }
       else
       {
           if(
$key==$search_str)
               return
1;
       }
   }
   return
0;   
}
?>
lordfarquaad at notredomaine dot net
09-Sep-2004 09:44
This function will be faster, as it doesn't compare all elements, it stops when it founds the good one. It also works if $haystack is not an array :-)

<?php
function in_array_multi($needle, $haystack)
{
   if(!
is_array($haystack)) return $needle == $haystack;
   foreach(
$haystack as $value) if(in_array_multi($needle, $value)) return true;
   return
false;
}
?>
<Marco Stumper> phpundhtml at web dot de
09-Sep-2004 09:49
Here is a function to search a string in multidimensional Arrays(you can have so much dimensions as you like:
function in_array_multi($needle, $haystack)
{
   $found = false;
   foreach($haystack as $value) if((is_array($value) && in_array_multi($needle, $value)) || $value == $needle) $found = true;
   return $found;
}

It is a little shorter than the other function.
mina86 at tlen dot pl
17-Aug-2004 09:16
A better (faster) version:
<?php
function in_array ($item, $array) {
  
$item = &strtoupper($item);
   foreach(
$array as $element) {
       if (
$item == strtoupper($element)) {
           return
true;
       }
   }
   return
false;
}
?>

Noah B, set the 3rd argument to true and everything will wokr fine :) 0 == 'foo' is true, however 0 === 'foo' is not.
php at NOSPAM dot fastercat dot com
24-Apr-2004 04:54
The description of in_array() is a little misleading. If needle is an array, in_array() and array_search() do not search in haystack for the _values_ contained in needle, but rather the array needle as a whole.

$needle = array(1234, 5678, 3829);
$haystack = array(3829, 20932, 1234);

in_array($needle, $haystack);
--> returns false because the array $needle is not present in $haystack.
 
Often people suggest looping through the array $needle and using in_array on each element, but in many situations you can use array_intersect() to get the same effect (as noted by others on the array_intersect() page):

array_intersect($needle, $haystack);
--> returns array(1234). It would return an empty array if none of the values in $needle were present in $haystack. This works with associative arrays as well.
fierojoe at fierojoe dot com
23-Mar-2004 03:03
I couldn't find an easy way to search an array of associative arrays and return the key of the found associative array, so I created this little function to do it for me. Very handy for searching through the results of a mysql_fetch_assoc()

<?php

$a
= array(
  array(
'id' => 1, 'name' => 'oranges'),
  array(
'id' => 2, 'name' => 'apples'),
  array(
'id' => 3, 'name' => 'coconuts'),
);

function
_array_search($s, $a) {
  for(
$i=0; $i <= count($a); $i++) {
   if (
in_array($s, $a[$i])) {
     return(
$i);
     break;
   }
  }
  return(
FALSE);
}

//returns key 0 for the second element, 'id' => 1
 
echo _array_search(1, $a);

//returns key 2 for the second element, 'id' => 3
 
echo _array_search(3, $a);

//returns key 1 for the second element, 'id' => 2
 
echo _array_search(2, $a);

?>
zapher at cae dot hl2files dot com
25-Feb-2004 02:59
I corrected one_eddie at tenbit dot pl 's  case-insensitive-script... It kinda didn't work :p

function in_array_cin($strItem, $arItems)
{
   $bFound = FALSE;
   foreach ($arItems as $strValue)
   {
       if (strtoupper($strItem) == strtoupper($strValue))
       {
           $bFound = TRUE;
       }
   }
   echo $bFound;
}
sean at natoewal dot nl
20-Feb-2004 06:56
For searching an object in array I made the ObjectArray class. An instance of this class is an array which contains the objects as strings which makes searching for objects possible.

<?php
class ObjectArray {
   var
$objectArray = array();
   function
ObjectArray() {
      
   }
   function
inArray($object) {
      
$needle = $this->object2String($object);
       return
in_array($needle, $this->objectArray);
   }
   function
object2String($object) {
      
$str = "";
      
$vars = get_object_vars($object);
       foreach (
$vars as $value)
          
$str .= (is_object($value)) ? $this->object2String($value) : $value;
       return
$str;
   }
   function
addObject($object) {
      
$str = $this->object2String($object); 
      
array_push($this->objectArray, $str);
   }
}
?>

You can use this class like:

<?php
$objectArray
= new ObjectArray();
$myFirstCar = new Car("brown", 20);
$objectArray->addObject($myFirstCar);
$mySecondCar = new Car("red", 160);
$objectArray->addObject($mySecondCar);
?>

This example uses the Car class:

<?php
class Car {
   var
$color;
   var
$speed;
   function
Car($color, $speed) {
      
$this->color = $color;
      
$this->speed = $speed;
   }   
}
?>

The next code shows an example if we were searching for my first car:

<?php
if ($objectArray->inArray($myFirstCar)) {
  echo
"I've found your first car!";
}
?>
one_eddie at tenbit dot pl
09-Feb-2004 07:16
I found no sample with case-insensitive in_array. Here's one i wrote:

function in_array_cin($strItem, $arItems)
{
   $bFound = FALSE;
   foreach ($arItems as str$Value)
   {
       if (strtpupper($strItem) == strtoupper($strValue))
           $bFound = TRUE;
   }
   return $bFound;   
}
Frank Sträter
14-Jan-2004 11:08
I forgot ta add $value === $needle instead of $value == $needle. The first one does a strict check. Thanks to the note by michi I have reduced the function to:

<?php

function in_array_multi($needle, $haystack) {
   if (!
is_array($haystack)) return false;
   while (list(
$key, $value) = each($haystack)) {
       if (
is_array($value) && in_array_multi($needle, $value) || $value === $needle) {
           return
true;
       }
   }
   return
false;
}

?>
mark at x2software dot net
09-Jan-2004 12:11
Reply/addition to melissa at hotmail dot com's note about in_array being much slower than using a key approach: associative arrays (and presumably normal arrays as well) are hashes, their keys are indexed for fast lookups as the test showed. It is often a good idea to build lookup tables this way if you need to do many searches in an array...

For example, I had to do case-insensitive searches. Instead of using the preg_grep approach described below I created a second array with lowercase keys using this simple function:

<?php
/**
 * Generates a lower-case lookup table
 *
 * @param array  $array      the array
 * @return array              an associative array with the keys being equal
 *                            to the value in lower-case
*/
function LowerKeyArray($array)
{
 
$result = array();

 
reset($array);
  while (list(
$index, $value) = each($array))
  {
  
$result[strtolower($value)] = $value;
  }

  return
$result;
}
?>

Using $lookup[strtolower($whatyouneedtofind)] you can easily get the original value (and check if it exists using isset()) without looping through the array every time...
gphemsley at users dot sourceforge dot net
02-Jan-2004 01:18
For those of you who need in_array() for PHP3, this function should do the trick.

<?php

function in_array( $needle, $haystack, $strict = FALSE )
{
   @
reset( $haystack );

   while( @list( ,
$value ) = @each( $haystack ) )
   {
       if(
$needle == $value )
       {
           if(
$strict && ( gettype( $needle ) != gettype( $value ) ) )
           {
               return
FALSE;
           }
           else
           {
               return
TRUE;
           }
       }
   }

   return
FALSE;
}

?>
Lee Benson
07-Nov-2003 05:36
If you're trying to compare a variable against several possible other variables, like this...

if ($var == 1 || $var == 2 || $var == 3 || $var == 4) {

   // do this

}

You can make your code a lot neater by doing this:

if (in_array($var,array(1,2,3,4))) {

  // do this

}

This way, you're not repeating the "$var == x ||" part of your expression over and over again.

If you've used MySQL's IN() function for searching on multiple values, you'll probably appreciate using this code in your PHP scripts.

Hope this helps a few people.
michi at F*CKSPAM michianimations dot de
26-Oct-2003 06:47
This is another solution to multi array search. It works with any kind of array, also privides to look up the keys instead of the values - $s_key has to be 'true' to do that - and a optional 'bugfix' for a PHP property: keys, that are strings but only contain numbers are automatically transformed to integers, which can be partially bypassed by the last paramter.

function multi_array_search($needle, $haystack, $strict = false, $s_key = false, $bugfix = false){

   foreach($haystack as $key => $value){

       if($s_key) $check = $key;
       else      $check = $value;

       if(is_array($value) &&
           multi_array_search($needle, $value, $strict, $s_key) || (

             $check == $needle && (

               !$strict ||
               gettype($check)  == gettype($needle) ||
               $bugfix  &&
               $s_key  &&
               gettype($key)    == 'integer' &&
               gettype($needle) == 'string'

             )
           )
       )

       return true;

   }

   return false;

}
morten at nilsen dot com
12-Aug-2003 12:00
either the benchmark I used, or the one used in an earlier comment is flawed, or this function has seen great improvement...

on my system (a Duron 1GHz box) the following benchmark script gave me pretty close to
1 second execution time average when used with 355000 runs of in_array() (10 runs)

<?php
  $average
= 0;
  for (
$run=0;$run<10;++$run) {
  
$test_with=array(
1=>array(explode(":",
":1:2:3:4:5:6:7:8:9:10:11:12:13:14:15:")),
2=>array(explode(":",
":21:22:23:24:25:26:27:28:29:210:211:212:213:214:215:")),
3=>array(explode(":",
":14:15:23:24:25:26:27:28:29:210:211:212:213:214:215:"))
   );
  
$start = microtime();
   for(
$i=0;$i<=355000;++$i) { in_array($i, $test_with); }
  
$end = microtime();
  
$start = explode(" ",$start);
  
$end = explode(" ",$end);
  
$start = $start[1].trim($start[0],'0');
  
$end  = $end[1].trim($end[0],'0');
  
$time  = $end - $start;
  
$average += $time;
   echo
"run $run: $time<br>";
  }
 
$average /= 10;
  echo
"average: $average";
?>
jr at jrmanes dot com
31-Jul-2003 01:35
/*
 ** A function that checks to see if a string in an array
 ** exists in a string.
 ** example:
 **  $string = "My name is J.R.";
 **  $array = array("Mike", "Joe", "Bob", "J.R.");
 **  if (arrayinstr($string, $array)) echo "Found it!";
 */

function arrayinstr($haystack, $needle) {
   $foundit = false;
   foreach($needle as $value) {
     if (!strpos($haystack, $value) === false)
         $foundit = true;
   }
   return $foundit;
}
raphinou at yahoo dot Com
22-Mar-2003 05:45
If the haystack contains the boolean true, in_array returns true!!
Check this (PHP 4.2.3-8 debian package) :

<?php
$r
=array("fzsgsdgsd","reazrazr","rezarzearzae",true);
$ret=in_array("tsuser_id",$r);

print
"<H1>__ $ret __</H1>";

}

?>
greg at serberus dot co dot uk
01-Feb-2003 06:48
With in_array() you need to specify the exact value held in an array element for a successful match. I needed a function where I could see if only part of an array element matched so I wrote this function to do it, it also searches keys of the array if required (only useful for associative arrays). This function is for use with strings:

function inarray($needle, $array, $searchKey = false)
{
   if ($searchKey) {
       foreach ($array as $key => $value)
           if (stristr($key, $needle)) {
               return true;
           }
       }
   } else {
       foreach ($array as $value)
           if (stristr($value, $needle)) {
               return true;
           }
       }
   }

   return false;
}
gordon at kanazawa-gu dot ac dot jp
07-Jan-2003 07:05
case-insensitive version of in_array:

function is_in_array($str, $array) {
  return preg_grep('/^' . preg_quote($str, '/') . '$/i', $array);
}
melissa at hotmail dot com
27-Dec-2002 02:53
With a bit of testing I've found this function to be quite in-efficient...

To demonstrate... I tested 30000 lookups in a consistant environment.  Using an internal stopwatch function I got approximate time of over 1.5 mins using the in_array function.

However, using an associative array this time was reduced to less than 1 second...

In short... Its probably not a good idea to use in_array on arrays bigger than a couple of thousand...

The growth is exponential...

 values
             in_array            assocative array
1000      00:00.05                  00:00.01
10000    00:08.30                  00:00.06
30000    01:38.61                  00:00.28
100000  ...(over 15mins)....    00:00.64

Example Code... test it out for yourself...:
//=============================================
$Count = 0;
$Blah = array();

while($Count<30000)
{
   if(!$Blah[$Count])
       $Blah[$Count]=1;

   $Count++;
}

echo "Associative Array";

$Count = 0;
$Blah = array();

while($Count<30000)
{
       if(!in_array($Count, $Blah))
           $Blah[] = $Count;

       $Count++;
}

echo "In_Array";
//=============================================
pingjuNOSPAM at stud dot NOSPAM dot ntnu dot no
25-Nov-2002 08:56
if the needle is only a part of an element in the haystack, FALSE will be returned, though the difference maybe only a special char like line feeding (\n or \r).
bbisgod AT hotmail DOT com
01-Oct-2002 07:17
I had a HUGE problem of comparing references to see if they were pointing to the same object.

I ended up using this code!

function in_o_array (&$needle, &$haystack) {
  if (!is_array($haystack)) return false;
  foreach ($haystack as $key => $val) {
   if (check_refs($needle, $haystack[$key])) return true;
  }
  return false;
}

function check_refs(&$a, &$b) {
  $tmp = uniqid("");
  $a->$tmp = true;
  $bResult = !empty($b->$tmp);
  unset($a->$tmp);
  return $bResult;
}

Hope this helps someone have a more productive morning that me! :P
leighnus at mbox dot com dot au
21-Aug-2002 02:18
Alternative method to find an array within an array (if your version of php doesn't support array type $needles):

function array_in_array($needle, $haystack) {
  foreach ($haystack as $value) {
   if ($needle == $value)
     return true;
  }
  return false;
}
tom at orbittechservices dot com
09-Aug-2002 09:17
I searched the general mailing list and found that in PHP versions before 4.2.0 needle was not allowed to be an array.

Here's how I solved it to check if a value is in_array to avoid duplicates;

$myArray = array(array('p', 'h'), array('p', 'r'));

$newValue = "q";
$newInsert = array('p','q');

$itBeInThere = 0;
foreach ($myArray as $currentValue) {
  if (in_array ($newValue, $currentValue)) {
   $itBeInThere = 1;
  }
if ($itBeInThere != 1) {
  array_unshift ($myArray, $newInsert);
}
robe_NO_SPAM at post_NO_SPAM dot cz
06-Aug-2002 05:32
In contribution of <jon@gaarsmand.dk>:

 I think we should use more general approach while walking through array, so instead your 'for' loop I'd suggest while list.. as follows:

function in_multi_array($needle, $haystack) //taken from php.net, adapted                                            {                                                                                                                                                                                                                                            $in_multi_array = false;                                                                                                if(in_array($needle, $haystack))                                                                                        {                                                                                                                    $in_multi_array = true;                                                                                            }                                                                                                                    else                                                                                                                {                                                                                                                                                                                    while (list($tmpkey,$tmpval) = each ($haystack))                                                                        //here is the change
{                                                                                                          if(is_array($haystack[$tmpkey])){                                                                                          if (in_multi_array($needle, $haystack[$tmpkey]))                                                                            {                                                                                                                    $in_multi_array = true;                                                                                              break;                                                                                                              }                                                                                                            }                                                                                                            }                                                                                                                }                                                                                                          return $in_multi_array;                                                                                          }     

I hope code is readible, some problems with formatting occured.
nicolaszujev at hot dot ee
19-Jul-2002 11:40
I wrote this function to check key in array and also check value if it exists...

function in_array_key($key, $array, $value = false)
{
   while(list($k, $v) = each($array))
   {
       if($key == $k)
       {
           if($value && $value == $v)
               return true;
           elseif($value && $value != $v)
               return false;
           else
               return true;
       }
   }
   return false;
}

.. very helpful function ...
01-Jul-2002 02:22
Looking at in_array, and array_search, I made up this small little example that does exactly what _I_ want.

<?php
$online
= array ("1337", "killer", "bob");
$find = array ("Damien", "bob", "fred", "1337");

while (list (
$key, $val) = each ($find)) {
  if (
in_array ($val, $online)) {
   echo
$val . "<br>";
  }
}
?>

Look for all instances of $find in $online. and print the element that was found.
penneyda at hotmail dot com
25-Jun-2002 01:23
If you are using in_array() to search through a file using the file() function, it seems you have to add the line break "\n".  It took me forever to figure out what the deal was.

Example:

$new_array = file("testing.txt");

if(in_array("$word_one : $word_two\n", $new_array))
   {
   print("success");
   exit;
   }
else
   {
   print("failure");
   exit;
   }

I just started learning PHP, but let me know if I have not figured this out correctly
one at groobo dot com
07-May-2002 05:14
Sometimes, you might want to search values in array, that does not exist. In this case php will display nasty warning:
Wrong datatype for second argument in call to in_array() .

In this case, add a simple statement before the in_array function:

if (sizeof($arr_to_searchin) == 0 || !in_array($value, $arr_to_searchin)) { ... }

In this case, the 1st statement will return true, omitting the 2nd one.
jon at gaarsmand dot dk
09-Apr-2002 10:53
If you want to search a multiple array for a value - you can use this function - which looks up the value in any of the arrays dimensions (like in_array() does in the first dimension).
Note that the speed is growing proportional with the size of the array - why in_array is best if you can determine where to look for the value.

Copy & paste this into your code...

function in_multi_array($needle, $haystack)
{
   $in_multi_array = false;
   if(in_array($needle, $haystack))
   {
       $in_multi_array = true;
   }
   else
   {   
       for($i = 0; $i < sizeof($haystack); $i++)
       {
           if(is_array($haystack[$i]))
           {
               if(in_multi_array($needle, $haystack[$i]))
               {
                   $in_multi_array = true;
                   break;
               }
           }
       }
   }
   return $in_multi_array;
}

<extractkey>
 Last updated: Thu, 19 May 2005
Copyright © 2001-2005 The PHP Group
All rights reserved.
This unofficial mirror is operated at: The Server Pages
Last updated: Thu May 19 17:35:34 2005 CDT