Documentation on in_array
in_array = Checks if a value exists in an array
Searches haystack for needle using loose comparison unless strict is set.
needle The searched value. Note: If needle is a string, the comparison is done in a case-sensitive manner. haystack The array. 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.
Usage, params, and more on in_array
bool in_array ( mixed $needle
, array $haystack
[, bool $strict
= FALSE
] )
needle
The searched value. Note: If needle
is a string, the comparison is done in a case-sensitive manner. haystack
The array. 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
.
Returns TRUE
if needle
is found in the array, FALSE
otherwise.
Notes and warnings on in_array
Basic example of how to use: in_array
Example #1 in_array() example
<?php
$os = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $os)) {
echo "Got Irix";
}
if (in_array("mac", $os)) {
echo "Got mac";
}
?>
The second condition fails because in_array() is case-sensitive, so the program above will display:
Got Irix
Example #2 in_array() with strict example
<?php
$a = array('1.10', 12.4, 1.13);
if (in_array('12.4', $a, true)) {
echo "'12.4' found with strict check\n";
}
if (in_array(1.13, $a, true)) {
echo "1.13 found with strict check\n";
}
?>
The above example will output:
1.13 found with strict check
Example #3 in_array() with an array as needle
<?php
$a = array(array('p', 'h'), array('p', 'r'), 'o');
if (in_array(array('p', 'h'), $a)) {
echo "'ph' was found\n";
}
if (in_array(array('f', 'i'), $a)) {
echo "'fi' was found\n";
}
if (in_array('o', $a)) {
echo "'o' was found\n";
}
?>
The above example will output:
'ph' was found 'o' was found
Other code examples of in_array being used
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
?>
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!
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));
}
?>
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;
}
?>
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;
}
?>
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;
}
?>
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!');
?>
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;
}
?>
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
?>
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.
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
?>
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;
}
?>
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';
}
?>
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;
}
?>
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
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.
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;
}
?>
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 ";
}
?>
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
?>
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;
}
?>
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;
}
?>