in_array

(PHP 4, PHP 5)

in_arrayPrüft, ob ein Wert in einem Array existiert

Beschreibung

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

Diese Funktion sucht in haystack nach needle. Wenn strict gesetzt ist wird dabei auch der Typ des Elements beachtet.

Parameter-Liste

needle

Der gesuchte Wert.

Hinweis:

Ist needle ein String so wird bei der Suche Groß- und Kleinschreibung beachtet.

haystack

Das zu durchsuchende Array.

strict

Wenn der dritte Parameter auf TRUE gesetzt wird vergleicht in_array() nicht nur den Wert sondern auch den Typ des gesuchten Wertes needle mit den Elementen des Arrays.

Rückgabewerte

Gibt TRUE zurück wenn needle im Array gefunden wird, sonst FALSE.

Changelog

Version Beschreibung
4.2.0 needle kann nun selbst ein Array sein.

Beispiele

Beispiel #1 in_array() Beispiel

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

Der zweite Vergleich schlägt fehl da in_array() Groß- und Kleinschreibung unterscheidet, die Ausgabe sieht daher so aus:

Irix enthalten

Beispiel #2 in_array() Beispiel mit 'strict'

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

if (
in_array('12.4'$atrue)) {
    echo 
"'12.4' bei strenger Prüfung gefunden\n";
}

if (
in_array(1.13$atrue)) {
    echo 
"1.13 Bei strenger Prüfung gefunden\n";
}
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

1.13 bei strenger Prüfung gefunden

Beispiel #3 in_array() mit Array als Suchwert

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

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

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

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

  'ph' gefunden
  'o' gefunden

Siehe auch

  • array_search() - Durchsucht ein Array nach einem Wert und liefert bei Erfolg den zugehörigen Schlüssel
  • isset() - Prüft, ob eine Variable existiert und ob sie nicht NULL ist
  • array_key_exists() - Prüft, ob ein Schlüssel in einem Array existiert

add a note add a note

User Contributed Notes 57 notes

up
67
beingmrkenny at gmail dot com
3 years ago
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

?>
up
12
Lea Hayes
3 years ago
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;
}
?>
up
16
Kelvin J
5 years ago
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));
    }
?>
up
14
bogdan AT bogdanconstantinescu DOT com
4 years ago
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;
    }
?>
up
11
jv at vip dot ie
4 years ago
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!
up
3
rolf dot dergham dot public at gmail dot com
10 months ago
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?
up
5
rhill at xenu-directory dot net
5 years ago
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.
up
4
janis dot janovskis at gmail dot com
2 years ago
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
?>
up
2
ctulek at gmail dot com
4 years ago
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.
up
1
crashrox at gmail dot com
6 years ago
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;
}
?>
up
1
musik at krapplack dot de
8 years ago
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
up
1
justinjohnmathews at gmail dot com
1 year ago
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';
    }
?>
up
1
sick949 at hotmail dot com
6 years ago
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;
}

?>
up
0
Chaya Cooper
1 month ago
To identify all instances of $needle when both $needle and $haystack are arrays, combine in_array() with a loop through the array  of needles.

I've posted a functional example of it here: http://sandbox.onlinephpfunctions.com/code/930385800c30595129cefb87cfa7eec9d69dce08

$needles = array('John', 'Alex');
$haystack = array('John','Alexander','Kim', 'Michael');

    foreach ($needles as $needle) {
        // Displays var name & value currently searching for)
        echo '$needle: '.$needle;
        if (in_array($needle, $haystack) ) {
            echo ', True; ';
        }
       else {
            echo ', False; ';
        }
    }

Result is:
$needle: John, True; $needle: Alex, False;
up
0
Chaya Cooper
1 month ago
To identify all instances of $needle when both $needle and $haystack are arrays, combine in_array() with a loop through the array  of needles.

I've posted a functional example of it here: http://sandbox.onlinephpfunctions.com/code/930385800c30595129cefb87cfa7eec9d69dce08

$needles = array('John', 'Alex');
$haystack = array('John','Alexander','Kim', 'Michael');

    foreach ($needles as $needle) {
        // Displays var name & value currently searching for)
        echo '$needle: '.$needle;
        if (in_array($needle, $haystack) ) {
            echo ', True; ';
        }
       else {
            echo ', False; ';
        }
    }

Result is:
$needle: John, True; $needle: Alex, False;
up
0
i dot pinz1 at gmail dot com
6 months ago
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.
up
0
Valerchik
1 year ago
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!
up
0
rajeevroy15 at gmail dot com dot com
2 years ago
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 ";
}
?>
up
0
Anonymous
3 years ago
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.
up
0
thomas dot sahlin at gmail dot com
5 years ago
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!');

?>
up
0
john at dwarven dot co dot uk
5 years ago
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

?>
up
-2
Artur K
1 year ago
As an addition to beingmrkennys note:

<?php

var_dump
(in_array('012', array('12'))); //returns true
var_dump(in_array('012', array('12'), true)); //returns false

?>

Seems like PHP is making some cast. So use the strict parameter.
up
0
Thingmand
5 years ago
A little function to use an array of needles:

<?php
function array_in_array($needles, $haystack) {

    foreach (
$needles as $needle) {

        if (
in_array($needle, $haystack) ) {
            return
true;
        }
    }

    return
false;
}
?>
up
0
brouwer dot p at gmail dot com
5 years ago
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;
  }
?>
up
0
selmand [at] gmail.com
5 years ago
Removes same text with in_array in a string.

<?

$hizmet="aeg,akai,aeg,arcelik,aeg,arcelik,klima,kombi";

// alots of same stings

$x=explode(",",$hizmet);

$t= array();
$k=0;
for($i=0;$i<sizeof($x);$i++){ // this for remove its
    //echo $x[$i]."\n";
    if(!in_array($x[$i],$t))
    {
        $t[$k]=$x[$i];
        $k++;
    }
   
}

for($i=0;$i<sizeof($t);$i++){ // rebuilding $hizmet strings.
   
    echo $t[$i].",";
   
}

?>
up
-1
Sascha Luedi
3 years ago
strange behaviour of in_array:

If you have an array like:
<?php
$a
= array(0,1,2,3,4,5);
in_array("bla", $a) returns true
in_array
("bla6", $a) returns true
in_array
("6bla", $a) returns false
?>

If you have an array like (without 0):
<?php
$a
= array(1,2,3,4,5);
in_array("bla", $a) returns false
in_array
("6bla", $a) returns false
in_array
("5bla", $a) returns true
?>

so better use strict arg!
up
0
Martijn Wieringa
6 years ago
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
up
0
sandrejev at gmail dot com
8 years ago
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;
}
?>
up
0
kitchin
8 years ago
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.
up
0
adrian foeder
9 years ago
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;
    }
?>
up
-1
Quaquaversal
7 years ago
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;
}
?>
up
-2
soxred93 at gmail dot com
5 years ago
Here's a simple little function I wrote that is a case insensitive version of in_array():

<?php
   
function in_arrayi( $needle, $haystack ) {
       
$found = false;
        foreach(
$haystack as $value ) {
            if(
strtolower( $value ) == strtolower( $needle ) ) {
               
$found = true;
            }
        }   
        return
$found;
    }
?>
up
-2
guitar king
6 years ago
In PHP 4, the first argument seems not allowed to be an object. In PHP 5, also objects are allowed as $needle.
up
-1
santi dot morel at gmail dot com
1 year ago
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;
    }
up
-1
Ray dot Paseur at Gmail dot com
3 years ago
Be VERY careful about testing for strings in arrays that might also contain integers.  In this snippet, the range() function turns the numeric values into integers, and loose data typing finds a match with zero.

Outputs:
PHP in_array() FOUND @#%?!!
@#%?!! == 0 AT POSITION 26 BECAUSE OF LOOSE TYPE

<?php // RAY_temp_in_array.php
error_reporting(E_ALL);
echo
"<pre>";

// THE ALLOWABLE SELECTIONS
$alpha = range('A','Z');
$alpha = array_merge($alpha, range('0', '9'));

// LOOK FOR A BOGUS SELECTION
$str = '@#%?!!';
if (
in_array($str, $alpha))
{
    echo
"PHP in_array() FOUND $str ";
}
else
{
    echo
"$str IS NOT IN ARRAY";
}

// SEARCH THE ARRAY FOR THE KEY OF THE STRING
$key = array_search($str, $alpha);
echo
"<br/>$str == $alpha[$key] AT POSITION $key";

if (
$str == 0) echo " BECAUSE OF LOOSE TYPE";
?>
up
-1
user at NOSPAM at fullservicead dot com
3 years ago
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.
up
-1
Fabian S
1 year ago
Robin's fast_in_array uses binary search, so the array has to be sorted before, using the regular sort function.
up
-1
bosdilooda at gmail dot com
3 years ago
There should be a big red warning sign here because this function behaves in mysterious ways...

let haystack be an array of integers:

$arr = array(1,2,3,4,5);

let $needle be a string of "2foobar"

then

in_array($needle,$arr)

will return true because string ("2foobar") evaluates to integer (2).
up
-1
natan dot volkovich at gmail dot com
4 years ago
If you're trying to find out whether or not at least a single value of an array matches a value in your haystack then use "array_intersect" instead of "in_array".

<?php
$needle
= array(1,2);
$haystack = array(0,1,2);

echo
"in_array: ".(int)in_array($needle, $haystack); // returns 0
echo "array_intersect: ".(int)array_intersect((array)$needle, $haystack); // returns 1
?>
up
-1
jordigirones at gmail dot com
5 years ago
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;
    }
?>
up
-1
info at b1g dot de
7 years ago
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
up
-1
tom at orbittechservices dot com
12 years ago
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;

<?php
$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);
}
?>
up
-3
Svinto
4 years ago
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
up
-1
what loose checking means
10 months ago
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.
up
-1
james dot ellis at gmail dot com
6 years ago
Be aware of oddities when dealing with 0 (zero) values in an array...

This script:
<?php
$array
= array('testing',0,'name');
var_dump($array);
//this will return true
var_dump(in_array('foo', $array));
//this will return false
var_dump(in_array('foo', $array, TRUE));
?>

It seems in non strict mode, the 0 value in the array is evaluating to boolean FALSE and in_array returns TRUE. Use strict mode to work around this peculiarity.
This only seems to occur when there is an integer 0 in the array. A string '0' will return FALSE for the first test above (at least in 5.2.6).
up
-1
james dot randell at hotmail dot co dot uk
6 years ago
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;
    }
?>
up
-2
robin at robinnixon dot com
5 years ago
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;
}
?>
up
-1
rick at fawo dot nl
8 years ago
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;
}
?>
up
-5
q*bist
2 years ago
version of in_array that searches by regular expression. Don't forget to preg_quote() your search term.

<?php

function in_array_match($regex, $array) {
    if (!
is_array($array))
       
trigger_error('Argument 2 must be array');
    foreach (
$array as $v) {
       
$match = preg_match($regex, $v);
        if (
$match === 1) {
            return
true;
        }
    }
    return
false;
}

?>
up
-4
chris at axxis dot gr
3 years ago
It's funny how PHP has an in_array method, but not an in_object one. Here is a simple function which will check if a value can be found within an object.

<?php
 
// in_object method
  // to check if a value in an object exists.
 
function in_object($value,$object) {
    if (
is_object($object)) {
      foreach(
$object as $key => $item) {
        if (
$value==$item) return $key;
      }
    }
    return
false;
  }
?>
 
This is very useful if an object has been created dynamically (especially from external code, which you don't control, as in an application-plugin, CMS, etc), and you don't know the object's properties.
The above function will return the property, so you will be able to use it in your code later on.

Here is a very good basic example of how useful this function is!

<?php
 
class My_Class {
    function
__construct($key, $value) {
     
$this->$key = $value;
     
// As you can see, this is a dynamic class, its properties and values can be unknown...
   
}
  }

  function
in_object($value,$object) {
    if (
is_object($object)) {
      foreach(
$object as $key => $item) {
        if (
$value==$item) return $key;
      }
    }
    return
false;
  }
 
  function
manipulate_property($value,$object) {
    if (
$property = in_object($value,$object)) {
     
// value found. I can now use this property.
      // I can simply echo'it (makes no sense, as I could instead simply echo "value")
     
echo "<br />I found the property holding this value: ".$object->$property;
     
// or (here comes the good part)
      // change the property
     
$object->$property = "This is a changed value!";
      echo
"<br />I changed the value to: ".$object->$property;
     
// or return it for use in my program flow
     
return $property;
    } else {
      echo
"Value NOT FOUND!<br />";
      return
false;
    }
  }
 
 
// imagine if some function creates the class conditionally...
 
if ( 1 == 1) {
   
$class = new My_Class("property","Unchanged Value");
  } else {
   
$class = new My_Class("property","Some Other Value");
  }
 
 
// now let's check if the value we want exists, and if yes, let's have some fun with it...
 
$property = manipulate_property("Unchanged Value",$class);
  if (
$property) {
   
$my_variable = $class->$property;
    echo
"<br />This is my variable now:".$my_variable;
  } else
$my_variable = $some_other_variable;
?>

Just run it to see for yourself!
up
-2
manuel at sunred dot org
10 months ago
If you are looking for a faster in_array function but still need the strict feature with which the type of element will be considered the following simple function might help you.

<?php
function fast_in_array($needle, array $haystack, $strict = false)
{
   
$c = count($haystack);
    if(
$strict !== true)
    {
        for(
$i = 0; $i < $c; $i++)
            if(
$haystack[$i] == $needle)
                return
true;
    }
    else
    {
        for(
$i = 0; $i < $c; $i++)
            if(
$haystack[$i] === $needle)
                return
true;
    }
    return
false;
}
?>
up
-2
me at bubjavier dot com
5 years ago
in case your haystack is undefined or not set:

<?php

$fruitExists
= in_array('mango', (array) $_SESSION["fruits"]);

?>

will return false if the haystack is not an array.
up
-2
Anonymous
8 years ago
in_arrayr -- Checks if the value is in an array recursively

Description
bool in_array (mixed needle, array haystack)

<?php
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
?>
up
-2
Aragorn5551 at gmx dot de
9 years ago
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.
up
-5
vladimir at vingrad dot ru
5 years ago
This function has Problem with UTF-8. To solve this Problem use:

in_array( mb_strtolower($tag, "UTF-8"), $arr)
up
-5
Joris Meijer
3 years ago
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.
up
-11
jemiaymen at gmail dot com
1 year ago
$a = array(1,5,2,15,88,8,7,9,10);

$b = array(4,10,5,11,15);

function similaire($a,$b){
    $result = array();
    $i =0;
    foreach($b as $var){

        if(in_array($var,$a)){
            $result[$i] = $var;
            $i++;
        }
    }
    return $result ;
}

var_dump($a);
var_dump($b);
var_dump(similaire($a,$b));

/*
output
array (size=9)
  0 => int 1
  1 => int 5
  2 => int 2
  3 => int 15
  4 => int 88
  5 => int 8
  6 => int 7
  7 => int 9
  8 => int 10

array (size=6)
  0 => int 4
  2 => int 10
  3 => int 5
  4 => int 11
  5 => int 15

array (size=4)
  1 => int 10
  2 => int 5
  3 => int 15

*/
To Top