PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

key> <extract
Last updated: Sat, 24 Mar 2007

view this page in

in_array

(PHP 4, PHP 5)

in_array — Ověřit, zda v poli existuje daná hodnota

Popis

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

Hledá v haystack hodnotu needle a pokud ji najde, vrací TRUE, jinak FALSE.

Pokud je třetí argument strict nastaven na TRUE, tak funkce in_array() také kontroluje typ needle v haystack.

Poznámka: Pokud je needle řetězec, tak porovnání rozlišuje velká a malá písmena.

Poznámka: V PHP starších než 4.2.0 nemohl být parametr needle pole.

Příklad 234. Ukázka in_array()

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

Druhá podmínka neuspěje, protože funkce in_array() rozlišuje velká a malá písmen, takže program vypíše:


Máme Irix

      

Příklad 235. Ukázka in_array() s parametrem strict

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

if (
in_array('12.4', $a, true)) {
    echo
"'12.4' bylo nalezeno s omezením strict\n";
}

if (
in_array(1.13, $a, true)) {
    echo
"1.13 bylo nalezeno s omezením strict\n";
}
?>

Vypíše:


1.13 bylo nalezeno s omezením strict

      

Příklad 236. in_array() při hledání pole

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

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

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

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

Vypíše:


  'ph' nalezeno
  'o' nalezeno

      

Viz také array_search(), array_key_exists() a isset().



key> <extract
Last updated: Sat, 24 Mar 2007
 
add a note add a note User Contributed Notes
in_array
Kureal at kkooporation dot de
18-Sep-2008 12:46
A notice to the, by alishanovin [at] hotmail. [dot] com released, in_array wrapper function:

You should use Pre-Increment, e.g. instead of "$i++" -> "++$i".
Pre-Incrementing is prooved to be 10 % faster, which makes a search-trip in a Thousand-Dimension-Array a quite faster.
Changed Version:

<?php

function in_wildarray($needle, $haystack, $case_sensitive=true) {
   
$is_wild = (!strpos($needle,"*")) ? false : true;
   
$needles = ($is_wild) ? explode("*", $needle) : array();
   
$needle = ($case_sensitive) ? $needle : strtolower($needle);
    for(
$i=0, $req = count($haystack);$i < $req; ++$i) {
       
$haystack_str = ($case_sensitive) ? $haystack[$i] : strtolower($haystack[$i]);
        if (
$is_wild) {
           
$found = false;
            for(
$x=0, $req = count($needles); $x < $req;++$x) {
               
$needle_index = strpos($haystack_str, trim($needles['x']));
               
$found = (!$needle_index) ? false : ($haystack_str = substr($haystack_str, 0, $needle_index ? true : false));
            }
            if (
$found) return true;
        } elseif (!
$is_wild && $haystack_str == $needle) {
            return
true;
        }
    }
    return
false;
}

?>

--
Kenan Sulayman
Application Designer,
KurealCorporation inc.
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;
    }
?>
alishahnovin at hotmail dot com
04-Sep-2008 12:33
Just caught a small bug in my code below...

As the code is right now, when there are wild cards, it will treat the initial segment as though it's preceded with a wild card. In other words, the first segment will be searched, not simply at the beginning of the string, but anywhere. Because it's a simple fix, I'll leave it to others. :)
alishahnovin at hotmail dot com
02-Sep-2008 12:43
Here's a function that does an in_array, but takes wildcards in the needle, and also can be case sensitive/insensitive...

A few points:
-It doesn't use foreach, but for, which is quicker
-I didn't use regex to search with a wildcard for the reason that the needle could be unpredictable if it's user-input, and rather than having to escape metacharacters, I decided it would be easier to do a plain text comparison.
-Needles with wildcards can come in many forms such as:

Str*ng
S*r*ng*
*rng
*i*n*

so a split is being done on that string, and each part is then compared with the current item. If the first part is not found, the comparison is done, and we move on. If it IS found, we move on to the next part of the needle, while chopping off the initial part of the haystack string. This is to ensure that each comparison of a needle part is looking at the next part of the haystack string.

For example:

needle: "Bo*bo"
haystack[0] = "Bob is lazy"

On the first pass, when searching "Bo", we then modify the haystack[0] to be: "b is lazy" so that "bo" is compared with that. Otherwise, we'd be comparing "bo" with "Bob is lazy", and returning true incorrectly.

I haven't fully tested the function, so let me know if you spot any bugs, or have any questions.

<?php

function in_wildarray($needle, $haystack, $case_sensitive=true) {
   
$is_wild = (strpos($needle,"*")===true)? true : false;
   
$needles = ($is_wild)? explode("*", $needle) : array();
   
$needle = ($case_sensitive)? $needle : strtolower($needle);
    for(
$i=0;$i<count($haystack);$i++) {
       
$haystack_str = ($case_sensitive)? haystack[$i] : strtolower($haystack[$i]);
        if (
$is_wild) {
           
$found = false;
            for(
$x=0;$x<count($needles);$x++) {
               
$needle_part = trim($needles[x]);
               
$needle_index = strpos($haystack_str, $needle_part);
                if (
$needle_index===false) {
                   
$found = false;
                    break;
//break out of the loop, because string part is not found in the haystack string
               
} else {
                   
$found = true;
                   
//chop off the start of the string to the needle_index
                    //so we can be sure that the found items are in the correct order
                    //and we are avoiding the potential of finding duplicate characters
                   
$haystack_str = substr($haystack_str, 0, $needle_index);
                }
            }
            if (
$found) { return true; }
        } elseif (!
$is_wild && $haystack_str == $needle) {
            return
true;
        }
    }
    return
false;
}

?>
com (dot) gmail (at) deceze
29-Aug-2008 02:04
Maybe the most efficient recursive in_array variation yet? ;)

<?php
function recursive_in_array($needle, $haystack) {
    foreach (
$haystack as $stalk) {
        if (
$needle == $stalk || (is_array($stalk) && recursive_in_array($needle, $stalk))) {
            return
true;
        }
    }
    return
false;
}
?>
Nemo Pohle
29-Aug-2008 12:32
This is another implementation of the in_arrayr() function found further down below which didn't really work (it returned upon finding the first nested array and ignoring all other nested arrays).

<?php
function in_arrayr($needle, $haystack, &$found = false) {
          foreach (
$haystack as $v) {
                  if (
$needle == $v) {
                   
$found = true;
                    return
true;
                  } elseif (
is_array($v)) {
                   
$this->in_arrayr($needle, $v, $found);
                  }
          }
         
          return
$found;
  }
?>
bfpdevel at gmail dot com
22-Jul-2008 10:58
@param mixed $key (string || array)

<?php
function inArray($array, $key)
{
  if(
func_num_args() == 2 && is_string($key))
    return
in_array($key, $array);
  else if(
func_num_args() == 2 && is_array($key))
  {
   
$r = true;
    for(
$i=0; $i < count($key); $i++)
     
$r = (!in_array($key[$i], $array)) ? false : $r;
   
    return
$r;
  }
  else if(
func_num_args > 2)
  {
   
$args = func_get_args();
   
$r = true;
    for(
$i=1; $i < count($args); $i++)
     
$r = (!in_array($args[$i], $array)) ? false : $r;
   
    return
$r;
  }
}

/* EXAMPLES */
$array = array('a', 'b', 'c', 'd', 'e', 'f');

// Example 1
if(inArray($array, 'b'))
  echo
'b is in array';

// Example 2
if(inArray($array, array('b', 'a', 'e')))
  echo
'a, b and e are in array';

// Example 3
if(inArray($array, 'b', 'a', 'e'))
  echo
'a, b and e are in 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;
}
?>
Gary Luck
12-Jul-2008 03:47
function to check a multidimensional array if a given array is in the "haystack".

<?
$Example_Needle['Art'] = 'Verb';
$Example_Needle['Verbform']['Finitiv'] = 1;

$Example_Haystack[5] = 2;
$Example_Haystack[7] = 'nein';
$Example_Haystack['ID'] = 1;
$Example_Haystack['Art'] = 'Verb';
$Example_Haystack['Verbform']['Finitiv'] = 1;
$Example_Haystack['Zeitform']['Präsens'] = 'ja';

function is_in_array($Needle, $Haystack){
    reset($Needle);
    while(list($Key, $Value) = each($Needle)){
        if(!array_key_exists($Key, $Haystack)){
            return false;
        }

        if(!is_array($Value)){
            if(in_array($Value, $Haystack)){
                $Return = true;
            }else{
                return false;
            }
        }else{
            if(is_in_array($Value, $Haystack[$Key])){
                $Return = true;
            }else{
                return false;
            }
        }
    }

    return $Return;
}

if(is_in_array($Example_Needle, $Example_Haystack)){
    echo 'yes';
}else{
    echo 'no';
}
?>

This will emit "yes". The given needle must be an array. A string as the needle is not supported in this function.
kyle dot florence ~at~ gmail dot com
27-Jun-2008 02:20
Improved (in readability, anyhow) multi-array search:

<?
 // Function for looking for a value in a multi-dimensional array
function in_multi_array($value, $array)
{   
    foreach ($array as $key => $item)
    {       
        // Item is not an array
        if (!is_array($item))
        {
            // Is this item our value?
            if ($item == $value) return true;
        }
      
        // Item is an array
        else
        {
            // See if the array name matches our value
            //if ($key == $value) return true;
          
            // See if this array matches our value
            if (in_array($value, $item)) return true;
          
            // Search this array
            else if (in_multi_array($value, $item)) return true;
        }
    }
  
    // Couldn't find the value in array
    return false;
}
?>

If you want the function to also match keys (such as if you are searching for an array called 'apple' inside of an array), uncomment this line:

<?
            //if ($key == $value) return true;
?>
PeeHPee
07-Jun-2008 12:01
<?php
    $pages
= array('help', 'main', 'contact');
    function
isDefined($page) {
        return
in_array($page, $pages, true);
     }
   
$act = $_GET['act'];
    function
loadPage() {
        if(
isDefined($act))
            include
$act . '.php';
        else
            include
'index.php';
    }
   
loadPage();
?>

Just wrote it so I could load pages, and if they're not defined in the array, I can load the default page.
David Zschille
20-May-2008 07:05
@Martijn Wieringa
read about the strict parameter.

<?php
var_dump
( in_array(0,   array(42),    true) );
var_dump( in_array(0,   array('42'),  true) );
var_dump( in_array(0,   array('Foo'), true) );
var_dump( in_array('0', array('Foo'), true) );
var_dump( in_array('0', array(0),     true) );
var_dump( in_array('0', array('0'),   true) );
?>
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
hadg
09-Apr-2008 05:18
ucffool, in your code you calculate the time for array_flip with isset. This is why isset time is bigger than in_array.

simply replace
        $time=microtime(1);
        $array2 = array_flip($array);
with
        $array2 = array_flip($array);
        $time=microtime(1);

to get isset's real time.
martin_p
08-Apr-2008 03:38
@mikegioia

And don't forget, that isset() looks for keys in arrays and in_array() looks for values. This could make also a significant difference in benchmarks, because the functions work in different ways.
trevorsg [at] gmail
05-Apr-2008 04:47
@rick (april 2006)

What is the point of making it case-insensitive and not using strtolower on both values? Fixed :)

<?php
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)==strtolower($value) : $item==$value;
        if(
$ret)
            return
$ret;
    }
    return
false;
}
?>
jony202 at gmail dot com
03-Apr-2008 07:06
<?php
function in_array_r($needle, $haystack)
{
   
$result = in_array($needle, $haystack);
    if (
$result) return $result;
    foreach (
$haystack as $v) {
        if (
is_array($v)) {
           
$result = in_array_r($needle, $v);
        }
        if (
$result) return $result;
    }
    return
$result;
}
?>
mikegioia
20-Mar-2008 12:49
@ vidmantas and ucffool:

There's a large difference between your methods of speed comparison. vidmantas is running in_array() and isset() in a for loop (once for each element of that large array) while ucffool just runs the functions.

I ran both speed tests and in_array() outperformed isset() every time.
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;
}

?>
ucffool
16-Feb-2008 11:51
@vidmantas
I had different results... Here is an example:

<?php
$array
= array();
for (
$x=1;$x <= 1000;$x++):
   
$array[] = mt_rand(100000,999999);
endfor;
$value = 123456;

$time=microtime(1);
if (
in_array($value,$array)):
    echo
"Found! ";
  else:
    echo
"Not found! ";
endif;
$time=number_format(microtime(1)-$time, 6);
echo
"Time to complete: " . $time;
echo
"<br />"; // -------------------------------------
$time=microtime(1);
$array2 = array_flip($array);
if (isset(
$array2[$value])):
    echo
"Found! ";
  else:
    echo
"Not found! ";
endif;
$time=number_format(microtime(1)-$time, 6);
echo
"Time to complete: " . $time;
?>

RESULT:
Not found! Time to complete: 0.000075
Not found! Time to complete: 0.000259

So I would say that on PHP5 at least, in_array seems to be more effective.
vidmantas dot norkus at neo dot lt
12-Feb-2008 09:16
Speed test on frequent search in array

<?php
//timer class
// php 4+
class WDM_Timer{
    var
$start;
   
    function
WDM_Timer(){
       
$this->start=$this->microtime_float();
    }
   
    function
microtime_float(){
        list(
$usec, $sec) = explode(" ", microtime());
        return (float)
$usec + (float)$sec;
    }
   
    function
stop($precision=2){
       
$precision=(int)$precision;
        return
sprintf("%01.{$precision}f",$this-> microtime_float() - (float)$this->start);
    }
}

//lets generate array
$ARR1=Array();
for(
$i=0;$i<10000;$i++){
   
$key=rand(100000000000000000, 1000000000000000000);
   
$ARR1[]=$key;

}

///==================================START TEST 1
$timer=new WDM_Timer();

foreach(
$ARR1 as $key => $val)
   
in_array($key,$ARR1);

echo
"TEST1 in_array(\$key,\$ARR) SEARCH. TIME ELAPSED: ".$timer->stop(10)."\n";

///==================================PREPARE TEST 2
//lets flip array, you can use $ARR2=array_flip($ARR1);
$ARR2=Array();
foreach(
$ARR1 as $key => $val)
   
$ARR2[$val]='';

//==================================START TEST2
$timer=new WDM_Timer();

foreach(
$ARR2 as $key => $val)
    isset(
$ARR[$key]);

echo
"TEST2 isset(\$ARR[\$key]) SEARCH. TIME ELAPSED: ".$timer->stop(10)."\n";
?>

test results on my server:

TEST1 in_array($key,$ARR) SEARCH. TIME ELAPSED: 8.5608828068
TEST2 isset($ARR[$key]) SEARCH. TIME ELAPSED: 0.0020029545
anonymous at vitut dot us
12-Feb-2008 06:55
in_array is pretty slow on big arrays, I used isset() instead in one of my projects. It works well if you are building the array yourself.

old way...

// build some array
while (something)
     $array[] = $value;

// use it to check something
if (in_array($search, $array)) {
     // something...
}

better way...

// build some array
while (something)
     $array[$value] = true;

// use it to check something
if (isset($array[$search])) {
     // something...
}

if you are using something like this, the improvement in speed is immense when using isset() instead of in_array()
guitar king
29-Jan-2008 11:52
In PHP 4, the first argument seems not allowed to be an object. In PHP 5, also objects are allowed as $needle.
lakinekaki at gmail dot com
05-Jan-2008 12:01
Breadcrumbs navigation for small sites with flat directory structure

Page levels are defined in a multidimensional array. Example array given below
<?php

$array
= array(
        
"contact",
        
"projects" ,
        
"projects" => array("architecture",
                        
"architecture" => array("flats","malls")),
        
"hobbies"
);

function
recursive_path($needle,$haystack,$current=''){
    if(!
is_array($haystack)) return '';
       
$ret='';
   
$csad = "$current > <b>$needle</b>";
    if(
in_array($needle,$haystack))return $csad;
    else{
        foreach(
$haystack as $key => $element){
           
$cposle = "$current > <a href=\"$key.html\">$key</a>";$ret .= recursive_path($needle,$element,$cposle);
        }
    }
    return
$ret;
}

// if current filename is needle, and site structure haystack, than this prints navigation path
echo recursive_path($filename,$array,'You are here: <a href="./">home</a>');

?>

I tried to do this without redundancies, but after many wasted hours, had to place 'duplicate' values for 'node' keys.

Suggestion for editors:

I was always impressed with this manual, and find it better than any other online programming resource. I wanted to find out more about the editing process behind it, and I discovered this:
http://news.php.net/php.notes/start/150000

Spending some time there, I saw quite a few useful scripts, and am therefore confused by their deletions. I can only assume that your level of knowledge is so far beyond of us regular PHP users, and to you most of scripts are obvious, that to us took a while to write.

Anyhow, here is suggestion: Since you already have almost dozen categories for managing notes, couldn't you send emails to authors informing them which decision was made. It would be informative and useful to do that. After all, if 'error' in the editing process is only 3%, it still results in almost 3000 very good notes deleted!

Thanks
f d0t fesser att gmx d0t net
16-Oct-2007 03:20
In case you have to check for unknown or dynamic variables in an array, you can use the following simple work-around to avoid misleading checks against empty and zero values (and only these "values"!):

<?php
  in_array
($value, $my_array, empty($value) && $value !== '0');
?>

The function empty() is the right choice as it turns to true for all 0, null and ''.
The '0' value (where empty() returns true as well) has to be excluded manually (as this is handled by in_array correctly!).

Examples:
<?php
  $val
= 0;
 
$res = in_array($val, array('2007'));
?>

leads incorrectly to true where

<?php
  $val
= 0;
 
$res = in_array($val, array('2007'), empty($val) && $val !== '0');
?>

leads correctly to false (strict check!) while

<?php
  $val
= 2007;
 
$res = in_array($val, array('2007'), empty($val) && $val !== '0');
?>

still correctly finds the '2007' ($res === true) because it ignores strict checking for that value.
info at b1g dot de
02-Aug-2007 10:44
Be careful with checking for "zero" in arrays when you are not in strict mode.
in_array(0, array()) == true
in_array(0, array(), true) == false
Quaquaversal
20-May-2007 08:48
A simple function to type less when wanting to check if any one of many values is in a single array.

<?php
function array_in_array($needle, $haystack) {
   
//Make sure $needle is an array for foreach
   
if(!is_array($needle)) $needle = array($needle);
   
//For each value in $needle, return TRUE if in $haystack
   
foreach($needle as $pin)
        if(
in_array($pin, $haystack)) return TRUE;
   
//Return FALSE if none of the values from $needle are found in $haystack
   
return FALSE;
}
?>
Bodo Graumann
16-Mar-2007 11:43
Be careful!

in_array(null, $some_array)
seems to differ between versions

with 5.1.2 it is false
but with 5.2.1 it's true!
ben
27-Feb-2007 01:25
Becareful :

$os = array ("Mac", "NT", "Irix", "Linux");
if ( in_array(0, $os ) )
   echo 1 ;
else
   echo 2 ;

This code will return 1 instead of 2 as you would waiting for.
So don't forget to add the TRUE parameter :

if ( in_array(0, $os ) )
   echo 1 ;
else
   echo 2 ;

Thie time it will return 2.
mike at php-webdesign dot nl
12-Feb-2007 01:11
@vandor at ahimsa dot hu

Why first check normal and then strict, make it more dynamically??

<?php
function in_arrayr($needle, $haystack, strict = false) {
    if(
$strict === false){
        foreach (
$haystack as $v) {
            if (
$needle == $v) return true;
            elseif (
is_array($v))
                if (
in_arrayr($needle, $v) == true) return true;
          }
        return
false;
    } else {
        foreach (
$haystack as $v) {
            if (
$needle === $v) return true;
            elseif (
is_array($v))
                if (
in_arrayr($needle, $v) === true) return true;
          }
        return
false;
    }
?>
mattsch at gmail dot com
26-Oct-2006 09:04
I'm not sure why you would do a loop for a function that needs to be fast.  There's an easier way:

function preg_array($strPattern, $arrInput){
        $arrReturn = preg_grep($strPattern, $arrInput);
        return (count($arrReturn)) ? true : 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;
}
?>
contact at simplerezo dot com
24-Feb-2006 08: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 07: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;
}
?>
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.
13-Jan-2006 09: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
10-Jan-2006 07: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
25-Nov-2005 02: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 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;
    }
?>
tacone at gmx dot net
03-Aug-2005 07: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
11-Jul-2005 09: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;
}
?>
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:
<?
$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.
greg at serberus dot co dot uk
17-May-2005 05: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 07: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.
lordfarquaad at notredomaine dot net
09-Sep-2004 07: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 07: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.
php at NOSPAM dot fastercat dot com
24-Apr-2004 02: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.
mark at x2software dot net
09-Jan-2004 10: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...
michi at F*CKSPAM michianimations dot de
26-Oct-2003 04: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 10: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";
?>
greg at serberus dot co dot uk
01-Feb-2003 04: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 05:05
case-insensitive version of in_array:

function is_in_array($str, $array) {
  return preg_grep('/^' . preg_quote($str, '/') . '$/i', $array);
}
meliss