in_array

(PHP 4, PHP 5, PHP 7)

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

说明

in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] ) : bool

大海捞针,在大海(haystack)中搜索针( needle),如果没有设置 strict 则使用宽松的比较。

参数

needle

待搜索的值。

Note:

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

haystack

待搜索的数组。

strict

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

返回值

如果找到 needle 则返回 TRUE,否则返回 FALSE

范例

Example #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

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

<?php
$a 
= array('1.10'12.41.13);

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

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

以上例程会输出:

1.13 found with strict check

Example #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() - 在数组中搜索给定的值,如果成功则返回首个相应的键名
  • isset() - 检测变量是否已设置并且非 NULL
  • array_key_exists() - 检查数组里是否有指定的键名或索引

User Contributed Notes

roman dot varuta at gmail dot com 06-Nov-2018 01:53
If array contain at least one true value, in_array() will return true every times if it is not false or null

Use strict = true

<?php

$arr
= array(true);

in_array($any, $arr); // Will return true every time except null and false

?>
iammanjil at gmail dot com 25-Oct-2018 08:00
If third parameter is not set to Strict then, the needle is found in haystack eventhought the values are not same. the limit behind the decimal seems to be 6 after which, the haystack and needle match no matter what is behind the 6th.

Wrong Response.
$os = array("652875063.10089021");
if (in_array("652875063.10089021", $os)) {
    echo "In Array";
}

Correct Response
$os = array("652875063.1008902");
if (in_array("652875063.1008901", $os)) {
    echo "In Array";
}
msegit post pl 18-Jul-2018 12:20
You can use my function inArray, to search:
- multidimensional arrays
- for substrings (case [in]sensitive)
- for sub-arrays
- get array of keys of found values
Look at github https://gist.github.com/msegu/80093a65316ded5b69558d5456f80ff9 (here is too long)
Carmen 15-Feb-2018 11:16
Esta función falla con las letras acentuadas y con las e?es. Por tanto, no sirve para los caracteres UTF-8.
El siguiente código falla para na cadena = "María Ma?as", no reconoce ni la "í" ni la "?":

    function validarNombreYApellidos ($cadena, $selector)
    {
        /* Se admiten las letras (he puesto sólo las mayusculas,
             porque paso la cadena con el nombre o
             el apellido a mayúscula antes de hacer la comparación),
             las vocales acentuadas, la diéresis,
             las e?es, los espacios en blanco y el guión
            (para los apellidos compuestos)*/
        $caracteresPermitidos =
               array ("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
                          "N", "?", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X",
                          "Y",  "Z", " ", "á", "é", "í", "ó", "ú", "ü", "-");
       
        $correcto = true;

        // ?La cadena está vacía?
        if (empty ($cadena))
        {
            $correcto = false;
        }
        else
        {
            $nombreOapellido = mb_strtoupper ($cadena, "utf-8");
            $longitudCadena = mb_strlen ($cadena, "utf-8");

            for ($i = 0; ($i < $longitudCadena) && $correcto; $i++)
            {
                if (!in_array ($nombreOapellido [$i],
                                     $caracteresPermitidos))
                {
                    // Se ha encontrado un carácter no permitido
                    $correcto = false;
                }
            }
        }
            return $correcto;
     }
Carmen 15-Feb-2018 11:15
Esta función falla con las letras acentuadas y con las e?es. Por tanto, no sirve para los caracteres UTF-8.
El siguiente código falla para na cadena = "María Ma?as", no reconoce ni la "í" ni la "?":

    function validarNombreYApellidos ($cadena, $selector)
    {
        /* Se admiten las letras (he puesto sólo las mayusculas,
             porque paso la cadena con el nombre o
             el apellido a mayúscula antes de hacer la comparación),
             las vocales acentuadas, la diéresis,
             las e?es, los espacios en blanco y el guión
            (para los apellidos compuestos)*/
        $caracteresPermitidos =
               array ("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
                          "N", "?", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X",
                          "Y",  "Z", " ", "á", "é", "í", "ó", "ú", "ü", "-");
       
        $correcto = true;

        // ?La cadena está vacía?
        if (empty ($cadena))
        {
            $correcto = false;
        }
        else
        {
            $nombreOapellido = mb_strtoupper ($cadena, "utf-8");
            $longitudCadena = mb_strlen ($cadena, "utf-8");

            for ($i = 0; ($i < $longitudCadena) && $correcto; $i++)
            {
                if (!in_array ($nombreOapellido [$i],
                                     $caracteresPermitidos))
                {
                    // Se ha encontrado un carácter no permitido
                    $correcto = false;
                }
            }
        }
            return $correcto;
     }
matthew dot scott dot day at gmail dot com 16-Nov-2017 12:12
var_dump(in_array(0, ['hello', 'world']));

returns true

var_dump(in_array(0, ['hello', 'world'], true));

returns false

Just posting this in case anyone else comes across 0 returning true for in_array
Geoffrey Hoffman 04-Aug-2017 04:00
Be careful to use the strict parameter with truth comparisons of specific strings like "false":

<?php

$truthy
= [true, 'true', 1, '1', 'y', 'Y', 'yes', 'YES'];

if (
in_array('false', $truthy)) {
   echo
"False is truthy.\n";
} else {
   echo
"False is not truthy.\n";
}

if (
in_array('false', $truthy, true)) {
    echo
"False is truthy.\n";
} else {
    echo
"False is not truthy.\n";
}

?>

The above example prints:

False is truthy.
False is not truthy.
stocki dot r at gmail dot com 02-Jun-2017 02:56
Add an extra if() to adrian foeder's comment to make it work properly:

<?php
   
...
    if (!@
$ret) {
       
$ret = rec_in_array($needle, $element, $alsokeys);
    }
    ...
?>

So this will work, too:

<?php
    $array
= array(
        array(
'a', 'b'),
        array(
'c', 'd')
    );
   
var_dump(rec_in_array('a', $array));
?>
php at koman dot com dot au 20-Jan-2017 05:12
The parameter section of this page states :-

   strict
      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.

I think a better explanation would be :-

   strict

      If the third parameter, strict, is set to TRUE, then the in_array() function will do a strict comparison of values and types between the needle and haystack.
 
      The default setting for the third parameter, strict, is FALSE, here the in_array() function will do type juggling in an attempt to match a value when a type is not the same between the needle and haystack.
rhuan at rhuan dot com dot br 31-Dec-2016 11:29
This code will search for a value in a multidimensional array with strings or numbers on keys.

function in_multiarray($elem, $array)
{
    while (current($array) !== false) {
        if (current($array) == $elem) {
            return true;
        } elseif (is_array(current($array))) {
            if (in_multiarray($elem, current($array))) {
                return true;
            }
        }
        next($array);
    }
    return false;
}
hoopyfroop at yahoo dot com 11-Nov-2016 02:14
If you search for numbers, in_array will convert any strings in your array to numbers, dropping any letters/characters, forcing a numbers-to-numbers comparison. So if you search for 1234, it will say that '1234abcd' is a match.  Example:

<?php
$test_array
= array('test', '1234abcd');
if (
in_array(1234, $test_array)) {
    echo
'1234 is a match!';
}
?>
tjamadeira at gmail dot com 29-Jan-2016 07:17
This function is for search a needle in a multidimensional haystack:

<?php
/**
 * A special function for search in a multidimensional array a needle
 *
 * @param mixed needle The searched variable
 * @param array haystack The array where search
 * @param bool strict It is or it isn't a strict search?
 *
 * @return bool
 **/
function in_array_r($needle, $haystack, $strict = false){
 foreach(
$haystack as $item){
   if(
is_array($item)){
     if(
in_array_r($needle, $item, $strict)){
       return
true;
     }
   }else{
     if((
$strict ? $needle === $item : $needle == $item)){
       return
true;
     }
   }
 }
 return
false;
}
?>
splogamurugan at gmail dot com 06-Nov-2015 11:49
var_dump(in_array('invalid', array(0,10,20)));
The above code gives true since the 'invalid' is getting converted to 0 and checked against the array(0,10,20)

but var_dump(in_array('invalid', array(10,20)));  gives 'false' since 0 not there in the array
dazero0 dot ls at gmail dot com 24-Sep-2015 10:43
I would like to add something to beingmrkenny at gmail dot com comparison post. After debugging a system, i discovered a security issue in our system and his post helped me find the problem.

In my additional testing i found out that not matter what you search for in an array, except for 0 and null, you get true as the result if the array contains true as the value.

Examples as php code :

<?php
$a
= ['a', 32, true, 'x' => y];
var_dump(in_array(25, $a)); // true, one would expect false
var_dump(in_array('ggg', $a)); // true, one would expect false

var_dump(in_array(0, $a)); // false
var_dump(in_array(null, $a)); // false
?>

Such the best practice in our case is to use strict mode. Which was not so obvious.
Harry Willis 24-Jan-2015 11:39
Kelvin's case-insensitive in_arrayi is fine if you desire loose typing, but mapping strtolower onto the array will (attempt to) cast all array members to string. If you have an array of mixed types, and you wish to preserve the typing, the following will work:

<?php
function in_array_ci($needle, array $haystack, $strict = false) {
    foreach (
$haystack as $element) {
        if (
gettype($needle) == 'string' && gettype($element) == 'string') {
            if (!
strcasecmp($needle, $element)) {
                return
true;
            }
        }
        elseif (
$strict) {
            if (
$needle === $element) {
                return
true;
            }
        }
        else {
            if (
$needle == $element) {
                return
true;
            }
        }
    }

    return
false;
}
?>
i dot pinz1 at gmail dot com 15-May-2014 11:33
I have noted some strange behavior of the in_array() function if you have a hash like
$haystack=array (
'123'=>'some value',
'0125'=>'some value');

If I test now:
if (in_array('23',$haystack)) // here also TRUE is returned

I switched instead to
if(isset($haystack['23'])) // which return correct FALSE

Maybe this helps others too.
what loose checking means 20-Jan-2014 05:03
In a high-voted example, an array is given that contains, amongst other things, true, false and null, against which various variables are tested using in_array and loose checking.

It impossible to receive false as a return value from in_array using loose checking if your arrays contains both the constants true and false. You might understandably trip over this (or the inverse - passing boolean true to check against an array of e.g. non-empty strings), but it's certainly not counter intuitive and makes perfect sense.
rolf dot dergham dot public at gmail dot com 13-Jan-2014 01:02
Watch out for this:

<?

print_r( (int) in_array('hello',array( 0 => 0)) );

?>

returns 1

Yes, it seems that is_array thinks that a random string and 0 are the same thing.
Excuse me, that's not loose checking, that's drunken logic.
Or maybe I found a bug?
santi dot morel at gmail dot com 22-May-2013 09:43
search in multidimensional array

    function in_multiarray($elem, $array) {
        foreach ($array as $key => $value) {
            if ($value==$elem){
                return true;
            }
            elseif(is_array($value)){
                if($this->in_multiarray($elem, $value))
                        return true;
            }
        }
       
        return false;
    }
Valerchik 13-May-2013 07:30
Beware when using this function to validate user input:

$a = array('0' => 'Opt 1', '1' => 'Opt 2', '2' => 'Opt 3');
$v = 'sql injection';
var_dump(in_array($v, array_keys($a)));

This will result : true;

array_keys($a) will cast array keys to int instead of string !
then when in_array will compare it will cast  'sql injection' to int 0 !
Beware of this!
justinjohnmathews at gmail dot com 05-Mar-2013 01:34
I think, "in_array" can be used with "range" function to check a number(dynamic value) is in between of other two numbers.

<?php
    $i
= 5; // Dynamic value   
   
if (in_array(range(1, 10), $i)) {
       echo
'Your number is in between of range array';
    }
?>
janis dot janovskis at gmail dot com 28-Feb-2012 11:03
Since sometimes in_array returns strange results - see notes above.
I was able to find value in array by this quite a simple function;
<?php
/**
* $find <mixed> value to find
* $array<array> array to search in
*/

function _value_in_array($array, $find){
 
$exists = FALSE;
 if(!
is_array($array)){
   return;
}
foreach (
$array as $key => $value) {
  if(
$find == $value){
      
$exists = TRUE;
  }
}
  return
$exists;
}

// Note
// You can't use wildcards and it does not check variable type
?>
rajeevroy15 at gmail dot com dot com 30-Nov-2011 04:51
is_array function checks only array only and giving incorrect result with multi-dimensional arrays.

Here is a custom function which will give the solution to check Array or Object and Checking of multi-dimensional arrays and objects as well.

<?php

function in_object($val, $obj){

    if(
$val == ""){
       
trigger_error("in_object expects parameter 1 must not empty", E_USER_WARNING);
        return
false;
    }
    if(!
is_object($obj)){
       
$obj = (object)$obj;
    }

    foreach(
$obj as $key => $value){
        if(!
is_object($value) && !is_array($value)){
            if(
$value == $val){
                return
true;
            }
        }else{
            return
in_object($val, $value);
        }
    }
    return
false;
}
?>
Usage  :
<?php

$array
= array("a", "b", "c"=>array("x", "y"=>array("p", "q"=>"r")));

if(
in_object("r", $arrX)){
    echo
"r is there ";
}else{
    echo
"Its not there ";
}
?>
beingmrkenny at gmail dot com 27-Oct-2011 03:35
Loose checking returns some crazy, counter-intuitive results when used with certain arrays. It is completely correct behaviour, due to PHP's leniency on variable types, but in "real-life" is almost useless.

The solution is to use the strict checking option.

<?php

// Example array

$array = array(
   
'egg' => true,
   
'cheese' => false,
   
'hair' => 765,
   
'goblins' => null,
   
'ogres' => 'no ogres allowed in this array'
);

// Loose checking -- return values are in comments

// First three make sense, last four do not

in_array(null, $array); // true
in_array(false, $array); // true
in_array(765, $array); // true
in_array(763, $array); // true
in_array('egg', $array); // true
in_array('hhh', $array); // true
in_array(array(), $array); // true

// Strict checking

in_array(null, $array, true); // true
in_array(false, $array, true); // true
in_array(765, $array, true); // true
in_array(763, $array, true); // false
in_array('egg', $array, true); // false
in_array('hhh', $array, true); // false
in_array(array(), $array, true); // false

?>
Lea Hayes 04-Aug-2011 05:40
Determine whether an object field matches needle.

Usage Example:
---------------

<?php
$arr
= array( new stdClass(), new stdClass() );
$arr[0]->colour = 'red';
$arr[1]->colour = 'green';
$arr[1]->state  = 'enabled';

if (
in_array_field('red', 'colour', $arr))
   echo
'Item exists with colour red.';
if (
in_array_field('magenta', 'colour', $arr))
   echo
'Item exists with colour magenta.';
if (
in_array_field('enabled', 'state', $arr))
   echo
'Item exists with enabled state.';
?>

Output:
--------
Item exists with colour red.
Item exists with enabled state.

<?php
function in_array_field($needle, $needle_field, $haystack, $strict = false) {
    if (
$strict) {
        foreach (
$haystack as $item)
            if (isset(
$item->$needle_field) && $item->$needle_field === $needle)
                return
true;
    }
    else {
        foreach (
$haystack as $item)
            if (isset(
$item->$needle_field) && $item->$needle_field == $needle)
                return
true;
    }
    return
false;
}
?>
Anonymous 18-Jun-2011 12:16
known issue
when checking a string vs a integer

$testarray = array(0,1,2,3,4);

in_array("bla", $a) returns true
in_array("bla6", $a) returns true
in_array("6bla", $a) returns false

"bla" as a integer value returns the number zero
"bla6" as a integer value returns the number zero
 "6bla" returns the number six as its the only vaild part of that

if you checking for unknown types eg string vs integer
then you would need the strict value to be true.
Joris Meijer 15-Feb-2011 05:31
A good option if your array contains objects and you wish to recursively search it (eg. with in_arrayr), is to use json_encode and json_decode first:

<?php

$array
= json_decode(json_encode($array_with_objects), true);

?>

In my opinion this is more elegant than a recursive in_array function which converts the objects into arrays while searching for a key and/or value.
user at NOSPAM at fullservicead dot com 02-Feb-2011 08:52
After reading all other notes about performance,
I made a little test.

fill an array in a loop with random characters,
shuffle it
search on it using 4 methods.

I tried to have haystack as array and string; hence the strstr.

I tried it on 9, 99, 999, 9999 elements and the results
remain in the same order:

9999 elements

Function :  execution time in miliseconds.

strstr : 1.2994079589844
fast_in_array : 1.0655579566956
isset : 0.99128198623657 //Winner, used from another note here.
in_array : 2.9410798549652

One last detail, I moved my functions around in the script to make sure there was no memory caching, reiteration op or whatever, it's all the same. in_array is the slowest and the use of isset($array[$NEEDLE]) the fastest.

I hope it saves somebody else the trouble.
ctulek at gmail dot com 30-Aug-2010 11:07
If you have an array like:
$arr = array(0,1,2,3,4,5);

in_array(NULL, $arr) returns true because you have 0 in your array. That is, in_array does not use === for equal check.
Svinto 22-May-2010 11:53
in_array() will always return true if a value in the haystack is of type bool(true).
This always hold except when the needle is of type bool(false).

Code:
<?php
$haystack
= array(true);
$needle = "anything except bool(false)";
$result = in_array($needle, $haystack);
var_dump($result); #Will always be true
?>

Solution:
run in_array() with strict set to true.
<?php
in_array
($needle, $haystack, true);
?>

Tested on PHP 5.2.6
bogdan AT bogdanconstantinescu DOT com 21-Apr-2010 08:01
If you found yourself in need of a multidimensional array in_array like function you can use the one below. Works in a fair amount of time

<?php

   
function in_multiarray($elem, $array)
    {
       
$top = sizeof($array) - 1;
       
$bottom = 0;
        while(
$bottom <= $top)
        {
            if(
$array[$bottom] == $elem)
                return
true;
            else
                if(
is_array($array[$bottom]))
                    if(
in_multiarray($elem, ($array[$bottom])))
                        return
true;
                   
           
$bottom++;
        }       
        return
false;
    }
?>
jv at vip dot ie 13-Feb-2010 04:46
If you're working with very large 2 dimensional arrays (eg 20,000+ elements) it's much faster to do this...

<?php
$needle
= 'test for this';

$flipped_haystack = array_flip($haystack);

if ( isset(
$flipped_haystack[$needle]) )
{
  print
"Yes it's there!";
}
?>

I had a script that went from 30+ seconds down to 2 seconds (when hunting through a 50,000 element array 50,000 times).

Remember to only flip it once at the beginning of your code though!
thomas dot sahlin at gmail dot com 05-Oct-2009 12:53
If you're creating an array yourself and then using in_array to search it, consider setting the keys of the array and using isset instead since it's much faster.

<?php

$slow
= array('apple', 'banana', 'orange');

if (
in_array('banana', $slow))
    print(
'Found it!');

$fast = array('apple' => 'apple', 'banana' => 'banana', 'orange' => 'orange');

if (isset(
$fast['banana']))
    print(
'Found it!');

?>
robin at robinnixon dot com 25-Jul-2009 12:38
This function is five times faster than in_array(). It uses a binary search and should be able to be used as a direct replacement:

<?php
function fast_in_array($elem, $array)
{
  
$top = sizeof($array) -1;
  
$bot = 0;

   while(
$top >= $bot)
   {
     
$p = floor(($top + $bot) / 2);
      if (
$array[$p] < $elem) $bot = $p + 1;
      elseif (
$array[$p] > $elem) $top = $p - 1;
      else return
TRUE;
   }
    
   return
FALSE;
}
?>
john at dwarven dot co dot uk 01-Jul-2009 04:34
I just struggled for a while with this, although it may be obvious to others.

If you have an array with mixed type content such as:

<?php

 $ary
= array (
  
1,
  
"John",
  
0,
  
"Foo",
  
"Bar"
 
);

?>

be sure to use the strict checking when searching for a string in the array, or it will match on the 0 int in that array and give a true for all values of needle that are strings strings.

<?php

var_dump
( in_array( 2, $ary ) );

// outputs FALSE

var_dump( in_array( 'Not in there', $ary ) );

// outputs TRUE

var_dump( in_array( 'Not in there', $ary, TRUE ) );

// outputs FALSE

?>
brouwer dot p at gmail dot com 08-Mar-2009 02:55
If made a in_array function that checks if the specified key matches. It works recursivly so it doesn't matter how deep your input array is.
<?php
 
function myInArray($array, $value, $key){
   
//loop through the array
   
foreach ($array as $val) {
     
//if $val is an array cal myInArray again with $val as array input
     
if(is_array($val)){
        if(
myInArray($val,$value,$key))
          return
true;
      }
     
//else check if the given key has $value as value
     
else{
        if(
$array[$key]==$value)
          return
true;
      }
    }
    return
false;
  }
?>
Kelvin J 28-Feb-2009 05:04
For a case-insensitive in_array(), you can use array_map() to avoid a foreach statement, e.g.:

<?php
   
function in_arrayi($needle, $haystack) {
        return
in_array(strtolower($needle), array_map('strtolower', $haystack));
    }
?>
jordigirones at gmail dot com 21-Jan-2009 07:54
function similar to in_array but implements LIKE '<string>%'

<?php
  
function in_array_like($referencia,$array){
      foreach(
$array as $ref){
        if (
strstr($referencia,$ref)){         
          return
true;
        }
      }
      return
false;
    }
?>
rhill at xenu-directory dot net 17-Jan-2009 01:05
I found out that in_array will *not* find an associative array within a haystack of associative arrays in strict mode if the keys were not generated in the *same order*:

<?php

$needle
= array(
   
'fruit'=>'banana', 'vegetable'=>'carrot'
   
);

$haystack = array(
    array(
'vegetable'=>'carrot', 'fruit'=>'banana'),
    array(
'fruit'=>'apple', 'vegetable'=>'celery')
    );

echo
in_array($needle, $haystack, true) ? 'true' : 'false';
// Output is 'false'

echo in_array($needle, $haystack) ? 'true' : 'false';
// Output is 'true'

?>

I had wrongly assumed the order of the items in an associative array were irrelevant, regardless of whether 'strict' is TRUE or FALSE: The order is irrelevant *only* if not in strict mode.
james dot randell at hotmail dot co dot uk 16-Sep-2008 02:54
Small method i built for my Array module, after looking through the manual I wanted a small compact way of making a wildcard search through an arrays values, and returning only those that it found.

<?php

   
/**
     * Takes a needle and haystack (just like in_array()) and does a wildcard search on it's values.
     *
     * @param    string        $string        Needle to find
     * @param    array        $array        Haystack to look through
     * @result    array                    Returns the elements that the $string was found in
     */
   
function find ($string, $array = array ())
    {       
        foreach (
$array as $key => $value) {
            unset (
$array[$key]);
            if (
strpos($value, $string) !== false) {
               
$array[$key] = $value;
            }
        }       
        return
$array;
    }
?>
crashrox at gmail dot com 21-Jul-2008 08:34
Recursive in array using SPL

<?php
function in_array_recursive($needle, $haystack) {

   
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($haystack));

    foreach(
$it AS $element) {
        if(
$element == $needle) {
            return
true;
        }
    }

    return
false;
}
?>
Martijn Wieringa 19-May-2008 02:20
When using numbers as needle, it gets tricky:

Note this behaviour (3rd statement):

in_array(0, array(42)) = FALSE
in_array(0, array('42')) = FALSE
in_array(0, array('Foo')) = TRUE
in_array('0', array('Foo')) = FALSE
sick949 at hotmail dot com 05-Mar-2008 03:43
A first idea for a function that checks if a text is in a specific column of an array.
It does not use in_array function because it doesn't check via columns.
Its a test, could be much better. Do not use it without test.

<?php

function in_array_column($text, $column, $array)
{
    if (!empty(
$array) && is_array($array))
    {
        for (
$i=0; $i < count($array); $i++)
        {
            if (
$array[$i][$column]==$text || strcmp($array[$i][$column],$text)==0) return true;
        }
    }
    return
false;
}

?>
musik at krapplack dot de 04-Jun-2006 05: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 08-Apr-2006 08: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;
}
?>
sandrejev at gmail dot com 22-Feb-2006 07:11
Sorry, that deep_in_array() was a bit broken.

<?php
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;
}
?>
kitchin 05-Feb-2006 06: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.
adrian foeder 08-Nov-2005 01: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;
    }
?>
Aragorn5551 at gmx dot de 11-Jun-2005 05: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:

<?php
$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.