in_array

(PHP 4, PHP 5)

in_array -- 检查数组中是否存在某个值

说明

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

haystack 中搜索 needle,如果找到则返回 TRUE,否则返回 FALSE

如果第三个参数 strict 的值为 TRUEin_array() 函数还会检查 needle类型是否和 haystack 中的相同。

注: 如果 needle 是字符串,则比较是区分大小写的。

注: 在 PHP 版本 4.2.0 之前,needle 不允许是一个数组。

例子 1. in_array() 例子

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

第二个条件失败,因为 in_array() 是区分大小写的,所以以上程序显示为:

Got Irix

例子 2. in_array() 严格类型检查例子

<?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";
}
?>

上例将输出:

1.13 found with strict check

例子 3. in_array() 中用数组作为 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";
}
?>

上例将输出:

'ph' was found
  'o' was found

参见 array_search()array_key_exists()isset()


add a note add a note User Contributed Notes
musik at krapplack dot de
04-Jun-2006 08:52
I needed a version of in_array() that supports wildcards in the haystack. Here it is:

<?php
function my_inArray($needle, $haystack) {
  
# this function allows wildcards in the array to be searched
  
foreach ($haystack as $value) {
       if (
true === fnmatch($value, $needle)) {
           return
true;
       }
   }
   return
false;
}

$haystack = array('*krapplack.de');
$needle = 'www.krapplack.de';

echo
my_inArray($needle, $haystack); # outputs "true"
?>

Unfortunately, fnmatch() is not available on Windows or other non-POSIX compliant systems.

Cheers,
Thomas
rick at fawo dot nl
09-Apr-2006 11:23
Here's another deep_in_array function, but this one has a case-insensitive option :)
<?
function deep_in_array($value, $array, $case_insensitive = false){
   foreach(
$array as $item){
       if(
is_array($item)) $ret = deep_in_array($value, $item, $case_insensitive);
       else
$ret = ($case_insensitive) ? strtolower($item)==$value : $item==$value;
       if(
$ret)return $ret;
   }
   return
false;
}
?>
Imre Pntek
05-Apr-2006 05:04
Beware that "Good morning"==0, so
<?php

$m
=array(0,"Hello");
var_dump(in_array("Good morning",$m));

?>
will output
bool(true)
so you will need to set strict.
contact at simplerezo dot com
25-Feb-2006 12:06
Optimized in_array insensitive case function:

function in_array_nocase($search, &$array) {
  $search = strtolower($search);
  foreach ($array as $item)
   if (strtolower($item) == $search)
     return TRUE;
  return FALSE;
}
sandrejev at gmail dot com
22-Feb-2006 11:11
Sorry, that deep_in_array() was a bit broken.

<?
function deep_in_array($value, $array) {
   foreach(
$array as $item) {
       if(!
is_array($item)) {
           if (
$item == $value) return true;
           else continue;
       }
      
       if(
in_array($value, $item)) return true;
       else if(
deep_in_array($value, $item)) return true;
   }
   return
false;
}
?>
sandrejev at gmail dot com
22-Feb-2006 02:21
Deep search form value

<?php
function deep_in_array($value, $array) {
   foreach(
$array as $item) {
       if(!
is_array($item)) continue;
       if(
in_array($value, $item)) return true;
       else if(
deep_in_array($value, $item)) return true;
   }
  
   return
false;
}
?>
czeslaw
18-Feb-2006 09:19
Searching multi arrays:

   function array_multi_search( $p_needle, $p_haystack )
   {
       if( !is_array( $p_haystack ) )
       {
           return false;
       }

       if( in_array( $p_needle, $p_haystack ) )
       {
           return true;
       }

       foreach( $p_haystack as $row )
       {
           if( array_multi_search( $p_needle, $row ) )
           {
               return true;
           }
       }

       return false;
   }
kitchin
05-Feb-2006 10:52
Here's a gotcha, and another reason to always use strict with this function.

$x= array('this');
$test= in_array(0, $x);
var_dump($test); // true

$x= array(0);
$test= in_array('that', $x);
var_dump($test); // true

$x= array('0');
$test= in_array('that', $x);
var_dump($test); // false

It's hard to think of a reason to use this function *without* strict.

This is important for validating user input from a set of allowed values, such as from a <select> tag.
eddie AT eddie punto cl
16-Jan-2006 09:07
The code in the note below didn't work for me the way i thought it would.
I had problems when it enter into the recursive array, if it found the needle it will return true, but the parent in_arrayr would not return true also.
so here is my correction to that function

<?php
function in_arrayr($needle, $haystack) {
   foreach (
$haystack as $value) {
       if (
$needle == $value) return true;
       elseif (
is_array($value))
           if (
in_arrayr($needle, $value))
               return
true;
   }
   return
false;
}
?>
com.hotmail@backglancer
15-Jan-2006 12:20
correction to the function below, the second return is bogous
here's my tweaked version

<?PHP
function in_arrayr($needle, $haystack) {
       foreach (
$haystack as $value) {
               if (
$needle == $value) return true;
               elseif (
is_array($value)) in_arrayr($needle, $value);
       }
       return
false;
}
?>
14-Jan-2006 01:44
in_arrayr -- Checks if the value is in an array recursively

Description
bool in_array (mixed needle, array haystack)

<?
function in_arrayr($needle, $haystack) {
       foreach (
$haystack as $v) {
               if (
$needle == $v) return true;
               elseif (
is_array($v)) return in_arrayr($needle, $v);
       }
       return
false;
}
// i think it works
?>
SBoisvert at Bryxal dot ca
11-Jan-2006 11:18
Many comments have pointed out the lack of speed of in_array (with a large set of items [over 200 and you'll start noticing) the algorithm is (O)n. You can achieve an immense boost of speed on changin what you are doing.

lets say you have an array of numerical Ids and have a mysql query that returns ids and want to see if they are in the array. Do not use the in array function for this you could easily do this instead.

if (isset($arrayOfIds[$Row['Id']))

to get your answer now the only thing for this to work is instead of creating an array like such

$arrayOfIds[] = $intfoo;
$arrayOfIds[] = $intfoo2;

you would do this:

$arrayOfIds[$intfoo] = $intfoo;
$arrayOfIds[$intfoo2] = $intfoo2;

The technical reason for this is array keys are mapped in a hash table inside php. wich means you'll get O(1) speed.

The non technical explanation is before is you had 100 items and it took you 100 microseconds for in_array with 10 000 items it would take you 10 000 microseconds. while with the second one it would still take you 100 microsecond if you have 100 , 10 000 or 1 000 000 ids.

(the 100 microsecond is just a number pulled out of thin air used to compare and not an actual time it may take)
juanjo
26-Nov-2005 06:59
Alternative method to find an array within an array with the haystack key returned

function array_in_array($needle, $haystack) {
  foreach ($haystack as $key => $value) {
   if ($needle == $value)
     return $key;
  }
  return false;
}
adrian foeder
08-Nov-2005 05:21
hope this function may be useful to you, it checks an array recursively (if an array has sub-array-levels) and also the keys, if wanted:

<?php
function rec_in_array($needle, $haystack, $alsokeys=false)
   {
       if(!
is_array($haystack)) return false;
       if(
in_array($needle, $haystack) || ($alsokeys && in_array($needle, array_keys($haystack)) )) return true;
       else {
           foreach(
$haystack AS $element) {
              
$ret = rec_in_array($needle, $element, $alsokeys);
           }
       }
      
       return
$ret;
   }
?>
mano at easymail dot hu
01-Nov-2005 07:19
Note, that in php's comparison table it says "php"==0 is true, so if:
(second table: http://www.php.net/manual/en/types.comparisons.php)

<?php

$foo
= in_array(0, array("x", "y")); // foo is TRUE!!!!! AAAH!

?>

because 0 and any string is equal. Of course, 0==="php" is not equal, false, but 0==="0" false too.

nice comparison tables by the way...

.mano
jpwaag at jpwaag dot com
25-Oct-2005 08:51
In case you want to check if multiple values are in your array, you can use this function:
<?php
function array_values_in_array($needles, $haystack) {
   if(
is_array($needles)){
      
$valid=true;
       foreach(
$needles as $needle){
           if(!
in_array($needle, $haystack)){
              
$valid=false;   
           }
       }
       return
$valid;
   }else{
       return
in_array($needles, $haystack);
   } 
}
//for example
$needles=array('ubuntu', 'gentoo', 'suse');
$haystack=array('ubuntu', 'gentoo', 'suse', 'knoppix', 'fedora', 'debian');
if(
array_values_in_array($needles, $haystack)){
   echo
'All the values of $needles are in $haystack';
}else{
   echo
'Some values of $needles are not in $haystack';
}

?>
adunaphel at il dot fontys dot nl
21-Oct-2005 05:48
a rewrite of alex at alexelectronics dot com's code, with the strict option added and some slight improvements in speed and readability:
<?php
 
function in_multi_array ($needle, $haystack, $strict) {
   if (
$strict) {
     foreach (
$haystack as $item) {
       if (
is_array ($item)) {
         if (
in_multi_array ($needle, $item, $strict)) {
           return
true;
         }
       } else {
         if (
$needle === $item) {
           return
true;
         }
       }
     }
   } else {
     foreach (
$haystack as $item) {
       if (
is_array ($item)) {
         if (
in_multi_array ($needle, $item, $strict)) {
           return
true;
         }
       } else {
         if (
$needle == $item) {
           return
true;
         }
       }
     }
   }
   return
false;
  }
?>
evildictaitor at hotmail dot com
13-Oct-2005 11:06
To look through a large array, it is much more efficient when it is sorted to use a binary chop method, so that the number of calls is equal to log(number_of_values_in_array) / log2 rather than equal to the number of values in the array.

For a million values in an array, it can therefore return whether this index exists in a file using no more than 20 calls to the array rather than a million. This makes it 50,000 times more efficient for an array of this size. I'm sure you can imagine what a million calls can do to a processor, and it isn't nice.

Hope this helps someone.
wcc at techmonkeys dot org
23-Sep-2005 10:04
<?php
/**
 * Search for a key and value pair in the second level of a multi-dimensional array.
 *
 * @param array multi-dimensional array to search
 * @param string key name for which to search
 * @param mixed value for which to search
 * @param boolean preform strict comparison
 * @return boolean found
 * @access public
 */ 
function findKeyValuePair($multiArray, $keyName, $value, $strict = false)
{
  
/* Doing this test here makes for a bit of redundant code, but
     * improves the speed greatly, as it is not being preformed on every
     * iteration of the loop.
     */
  
if (!$strict)
   {
       foreach (
$multiArray as $multiArrayKey => $childArray)
       {
           if (
array_key_exists($keyName, $childArray) &&
              
$childArray[$keyName] == $value)
           {
               return
true;
           }
       }
   }
   else
   {
       foreach (
$multiArray as $multiArrayKey => $childArray)
       {
           if (
array_key_exists($keyName, $childArray) &&
              
$childArray[$keyName] === $value)
           {
               return
true;
           }
       }
   }

   return
false;
}
?>
tacone at gmx dot net
03-Aug-2005 10:05
Beware of type conversion!

This snippet will unset every 0 key element form the array, when cycling an array which contains at least one _num value.
This is because php tries to convert every element of $forbidden_elements to integer when encountering a numeric index into array.
So $array[0] it's considered equal to (int)'_num'.

<?php
$forbidden_elements
=array('_num');
   foreach (
$array as $key=>$value){       
       if (
in_array($key,$forbidden_elements)){               
               unset (
$array[$key]);       
           }
}
?>

The following example works, anway you can use strict comparison as well.

<?php
$forbidden_elements
=array('_num');
   foreach (
$array as $key=>$value){       
       if (
in_array($key,$forbidden_elements) && is_string($key)){               
               unset (
$array[$key]);       
           }
}
?>
alex at alexelectronics dot com
12-Jul-2005 12:42
Actually, that should be

<?PHP
function in_multi_array($needle, $haystack) {
  
$in_multi_array = false;
   if(
in_array($needle, $haystack)) {
      
$in_multi_array = true;
   } else {
       foreach (
$haystack as $key => $val) {
           if(
is_array($val)) {
               if(
in_multi_array($needle, $val)) {
                  
$in_multi_array = true;
                   break;
               }
           }
       }
   }
   return
$in_multi_array;
}
?>
rob at bronco dot co dot uk
01-Jul-2005 08:23
For the "rediculous behaviour", a populated array is bool(true). This is documented.

<?php
var_dump
((bool)Array(false)); // bool(true)
var_dump((bool)Array()); // bool(false)
?>
alex at alexelectronics dot com
01-Jul-2005 12:24
A foreach would be simpler for a multi-dimensional array search (and probably faster, since you an use the value instead of the index).  Like this:

<?PHP
function in_multi_array($needle, $haystack) {
  
$in_multi_array = false;
   if(
in_array($needle, $haystack)) {
      
$in_multi_array = true;
   } else {
       foreach
$haystack as ($key => $val) {
           if(
is_array($val)) {
               if(
in_multi_array($needle, $val)) {
                  
$in_multi_array = true;
                   break;
               }
           }
       }
   }
   return
$in_multi_array;
}
?>

Using is_array($val) is probably faster than using is_array($haystack[$key])
Aragorn5551 at gmx dot de
11-Jun-2005 08:26
If you have a multidimensional array filled only with Boolean values like me, you need to use 'strict', otherwise in_array() will return an unexpected result.

Example:
<?
$error_arr
= array('error_one' => FALSE, 'error_two' => FALSE, array('error_three' => FALSE, 'error_four' => FALSE));

if (
in_array (TRUE, $error_arr)) {
   echo
'An error occurred';
}
else {
   echo
'No error occurred';
}
?>

This will return 'An error occurred' although theres no TRUE value inside the array in any dimension. With 'strict' the function will return the correct result 'No error occurred'.

Hope this helps somebody, cause it took me some time to figure this out.
19-May-2005 10: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 08: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 10: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.
09-Mar-2005 10: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
08-Mar-2005 06: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.
23-Dec-2004 06: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 11: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 06: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
10-Sep-2004 10: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 10: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 10: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
25-Apr-2004 05: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
24-Mar-2004 05: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
26-Feb-2004 04: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
21-Feb-2004 08: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
10-Feb-2004 09: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 Strter
15-Jan-2004 01: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
10-Jan-2004 02: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 03: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
08-Nov-2003 07: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
27-Oct-2003 08: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
13-Aug-2003 01: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
01-Aug-2003 02: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
23-Mar-2003 07: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 08: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
08-Jan-2003 09: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 04: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 10: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 08: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 03: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
10-Aug-2002 10: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 06: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
20-Jul-2002 12: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 ...
02-Jul-2002 03: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
26-Jun-2002 02: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
08-May-2002 06: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 11: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;
}