PHP: in_array - Manual

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, 27 Jan 2007

view this page in

# in_array

(PHP 4, PHP 5)

in_array -- Проверить, присутствует ли в массиве значение

## Описание

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

Ищет в `haystack` значение `needle` и возвращает `TRUE` в случае удачи, `FALSE` в противном случае.

Если третий параметр `strict` установлен в `TRUE` тогда функция in_array() также проверит соответствие types параметра `needle` и соответствующего значения массива `haystack`.

> Замечание: Если `needle` - строка, сравнение будет регистрозависмым.

> Замечание: В PHP версий, более ранних, чем 4.2.0 параметр `needle` не может быть массивом.

Пример 1. Пример использования in_array()

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

Второго совпадения не будет, потому что in_array() регистрозависима, таким образом, программа выведет:

    Got Irix

Пример 2. Пример использования in_array() с параметром strict

`<?php
$a = array('1.10', 12.4, 1.13);
if (in_array('12.4', $a, true)) {
echo "'12.4' found with strict check
";
}
if (in_array(1.13, $a, true)) {
echo "1.13 found with strict check
";
}
?>`

Результат выполнения данного примера:

    1.13 found with strict check

Пример 3. Пример использования in_array() с массивом в качестве параметра needle

`<?php
$a = array(array('p', 'h'), array('p', 'r'), 'o');
if (in_array(array('p', 'h'), $a)) {
echo "'ph' найдено
";
}
if (in_array(array('f', 'i'), $a)) {
echo "'fi' найдено
";
}
if (in_array('o', $a)) {
echo "'o' найдено
";
}
?>`

Результат выполнения данного примера:

    'ph' найдено
      'o' найдено

См. также array_search(), array_key_exists() и isset().

add a note User Contributed Notes
in_array
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;
}
?>`
vandor at ahimsa dot hu
05-Jan-2007 03:20
`this "14-Jan-2006 06:44" example correctly:
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)) {
if (in_arrayr($needle, $v) === true) return true;
}
}
return false;
}
?>`
RQuadling at GMail dot com
29-Nov-2006 05:08
`In trying to emulate a case insensitive in_array(), I came up with ...
<?php
function in_array_caseless($m_Needle, array $a_Haystack, $b_Strict = False)
{
// Let's assume the function will fail.
$b_Result = False;
// Compare array vs array
if (is_array($m_Needle))
{
// Iterate the Haystack to compare each Bale with the Needle.
foreach($a_Haystack as $a_Bale)
{
// Determine the intersection between the Needle and the Bale.
// Strictness indicates that the associative indexes must also match using case insensitivity.
if (
($b_Strict && (array_uintersect_uassoc($m_Needle, $a_Bale, 'strcasecmp', 'strcasecmp') === $m_Needle)) ||
(!$b_Strict && (array_uintersect($m_Needle, $a_Bale, 'strcasecmp') === $m_Needle))
)
{
// It it matches then we have a winner.
$b_Result = True;
// Don't process anything else as 1 match is all that is required.
break;
}
}
}
// Compare everything else but reverse the Haystack and the Needle.
// This is done as the return from array_uinterect is based upon its Needle
// and we need the Haystack's type to compare for strictness.
else
{
$a_Result = array_values(array_uintersect($a_Haystack, array($m_Needle), 'strcasecmp'));
$b_Result = !$b_Strict || (gettype($m_Needle) == gettype($a_Result[0]));
}
// Return the result
return $b_Result;
}
?>
For more info on this and other cool functions please see http://rquadling.php1h.com.`
lafo
26-Nov-2006 08:36
`The specification of this function is misleading.
<?php
$os = array("mac"=>"Mac", "NT", "Irix", "Linux");
if (in_array("mac", $os)) {
echo "Got mac";
}
// prints Got mac !!!
?>
in_array searches both values AND indexes IF it is not running in the strict mode!
Correct specification: Checks if a value or a key exists in an array. In the strict mode, checks if a value exists in an array.`
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;
}`
nongjianz at yahoo dot com
16-Sep-2006 06:08
`in_array does not work for this case:
If all items of an array as elements (not as an array) are in another array. For example:
$arr1 = array("aaa", "bbb", "ccc", "ddd");
$arr2 = array("aaa", "bbb");
The following function is a solution to work it out:
<?
function arrElement_in_array($arr2, $arr1){
foreach($arr2 as $v){
if(in_array($v, $arr1)){
$count++;
}
}
//if all elements of arr2 are in arr1
if($count==count($arr2)){
return true;
}
}
?>`
emailfire at gmail dot com
17-Jul-2006 08:46
`This function allows you to use regular expressions to search the array:
<?php
function preg_array($pattern, $array)
{
$match = 0;
foreach ($array as $key => $value)
{
if (preg_match($pattern, $value))
{
$match = 1;
break;
}
}
return ($match == 1) ? true : false;
}
?>
An example:
<?php
$colors = array('red', 'green', 'blue');
if (preg_array("/green/i", $colors)) {
echo "Match found!";
}
else {
echo "Match not found!";
}
?>`
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;
}
?>`
Imre Péntek
04-Apr-2006 02:04
`Beware that "Good morning"==0, so
<?php
$m=array(0,"Hello");
var_dump(in_array("Good morning",$m));
?>
will output
bool(true)
so you will need to set strict.`
contact at simplerezo dot com
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;
}
?>`
czeslaw
18-Feb-2006 05:19
`Searching multi arrays:
function array_multi_search( $p_needle, $p_haystack )
{
if( !is_array( $p_haystack ) )
{
return false;
}
if( in_array( $p_needle, $p_haystack ) )
{
return true;
}
foreach( $p_haystack as $row )
{
if( array_multi_search( $p_needle, $row ) )
{
return true;
}
}
return false;
}`
kitchin
05-Feb-2006 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;
}
?>`
mano at easymail dot hu
01-Nov-2005 03:19
`Note, that in php's comparison table it says "php"==0 is true, so if:
(second table: http://www.php.net/manual/en/types.comparisons.php)
<?php
$foo = in_array(0, array("x", "y")); // foo is TRUE!!!!! AAAH!
?>
because 0 and any string is equal. Of course, 0==="php" is not equal, false, but 0==="0" false too.
nice comparison tables by the way...
.mano`
jpwaag at jpwaag dot com
25-Oct-2005 05:51
`In case you want to check if multiple values are in your array, you can use this function:
<?php
function array_values_in_array($needles, $haystack) {
if(is_array($needles)){
$valid=true;
foreach($needles as $needle){
if(!in_array($needle, $haystack)){
$valid=false;
}
}
return $valid;
}else{
return in_array($needles, $haystack);
}
}
//for example
$needles=array('ubuntu', 'gentoo', 'suse');
$haystack=array('ubuntu', 'gentoo', 'suse', 'knoppix', 'fedora', 'debian');
if(array_values_in_array($needles, $haystack)){
echo 'All the values of $needles are in $haystack';
}else{
echo 'Some values of $needles are not in $haystack';
}
?>`
adunaphel at il dot fontys dot nl
20-Oct-2005 02:48
`a rewrite of alex at alexelectronics dot com's code, with the strict option added and some slight improvements in speed and readability:
<?php
function in_multi_array ($needle, $haystack, $strict) {
if ($strict) {
foreach ($haystack as $item) {
if (is_array ($item)) {
if (in_multi_array ($needle, $item, $strict)) {
return true;
}
} else {
if ($needle === $item) {
return true;
}
}
}
} else {
foreach ($haystack as $item) {
if (is_array ($item)) {
if (in_multi_array ($needle, $item, $strict)) {
return true;
}
} else {
if ($needle == $item) {
return true;
}
}
}
}
return false;
}
?>`
wcc at techmonkeys dot org
23-Sep-2005 07:04
`<?php
/**
* Search for a key and value pair in the second level of a multi-dimensional array.
*
* @param array multi-dimensional array to search
* @param string key name for which to search
* @param mixed value for which to search
* @param boolean preform strict comparison
* @return boolean found
* @access public
*/
function findKeyValuePair($multiArray, $keyName, $value, $strict = false)
{
/* Doing this test here makes for a bit of redundant code, but
* improves the speed greatly, as it is not being preformed on every
* iteration of the loop.
*/
if (!$strict)
{
foreach ($multiArray as $multiArrayKey => $childArray)
{
if (array_key_exists($keyName, $childArray) &&
$childArray[$keyName] == $value)
{
return true;
}
}
}
else
{
foreach ($multiArray as $multiArrayKey => $childArray)
{
if (array_key_exists($keyName, $childArray) &&
$childArray[$keyName] === $value)
{
return true;
}
}
}
return false;
}
?>`
tacone at gmx dot net
03-Aug-2005 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;
}
?>`
rob at bronco dot co dot uk
01-Jul-2005 05:23
`For the "rediculous behaviour", a populated array is bool(true). This is documented.
<?php
var_dump((bool)Array(false)); // bool(true)
var_dump((bool)Array()); // bool(false)
?>`
alex at alexelectronics dot com
30-Jun-2005 09:24
`A foreach would be simpler for a multi-dimensional array search (and probably faster, since you an use the value instead of the index). Like this:
<?PHP
function in_multi_array($needle, $haystack) {
$in_multi_array = false;
if(in_array($needle, $haystack)) {
$in_multi_array = true;
} else {
foreach $haystack as ($key => $val) {
if(is_array($val)) {
if(in_multi_array($needle, $val)) {
$in_multi_array = true;
break;
}
}
}
}
return $in_multi_array;
}
?>
Using is_array($val) is probably faster than using is_array($haystack[$key])`
Aragorn5551 at gmx dot de
11-Jun-2005 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.`
08-Mar-2005 06:15
`I'd have to disagree with the previous poster. The behavior is not "completely as expected." If I do not know what data is in an array, and I search for the value "123abc", I certainly don't expect it to match the integer 123. I expect it to match the string "123abc," period. The needle should not be converted for the sake of comparison! In the case of a string in the haystack or needle, the other value should be converted to a string before comparison. This guarantees only equivalent values will be matched.
This kind of behavior is the reason I always use === in PHP instead of ==. Too many things match otherwise. Luckily, the "strict" option here gives the right results.
-Dan`
Chris
07-Mar-2005 02:02
`I hope everyone sees that the previous poster's comments are incorrect, in that the behavior is not ridiculous but completely as expected.
> in_array('123abc', array(123)) returns true
A string is being compared to an integer, in such a situation PHP assumes an integer context wherein '123abc' evaluates to the integer 123, thus a match.
> in_array('123abc', array('123')) returns false
A string is being compared to a string and OBVIOUSLY these strings are not equal.`
22-Dec-2004 02:51
`Please note this very ridiculous behaviour:
in_array('123abc', array(123)) returns true
in_array('123abc', array('123')) returns false
I guess this is because it is converting '123abc' to an int.`
memandeemail at gmail dot com
17-Nov-2004 07:55
`Some very helpfuly variant's, of functions:
class shared {
/**lordfarquaad at notredomaine dot net 09-Sep-2004 11:44
* @return bool
* @param mixed $needle
* @param mixed $haystack
* @desc This function will be faster, as it doesn't compare all elements, it stops when it founds the good one. It also works if $haystack is not an array :-)
*/
function in_array_multi($needle, $haystack)
{
if(!is_array($haystack)) return $needle == $haystack;
foreach($haystack as $value) if(shared::in_array_multi($needle, $value)) return true;
return false;
}
/**lordfarquaad function's variant1
* @return bool
* @param string $needle_key
* @param mixed $haystack
* @desc Search a key in the array and return if founded or not.
*/
function in_array_key_multi($needle_key, $haystack)
{
if(!is_array($haystack)) return $needle_key == $haystack;
foreach($haystack as $key => $value)
{
$value; // TODO: Extract the $key without seting $value
if(shared::in_array_key_multi($needle_key, $key)) return true;
}
return false;
}
/**lordfarquaad function's variant2
* @return bool
* @param string $needlekey
* @param mixed $needlevalue
* @param mixed[optional] $haystack_array
* @param string[optional] $haystack_key
* @param mixed[optional] $haystack_value
* @desc Search in array for the key and value equal.
*/
function in_array_multi_and_key($needlekey, $needlevalue, $haystack_array = null, $haystack_key = null, $haystack_value = null)
{
if (!is_array($haystack_array)) return ($needlekey == $haystack_key and $needlevalue == $haystack_value);
foreach ($haystack_array as $key => $value) if (shared::in_array_multi_and_key($needlekey, $needlevalue, $value, $key, $value)) return true;
return false;
}
}
HOW TO USE:
shared::in_array_multi(......)
it's very simple.`
langewisch at lakoma dot com
04-Nov-2004 02:13
`Hi,
if you want to search a value in a mutidimensional array try this.
Cu
Christoph
-------------------------------
<?
function in_multi_array($search_str, $multi_array)
{
if(!is_array($multi_array))
return 0;
if(in_array($search_str, $multi_array))
return 1;
foreach($multi_array as $key => $value)
{
if(is_array($value))
{
$found = in_multi_array($search_str, $value);
if($found)
return 1;
}
else
{
if($key==$search_str)
return 1;
}
}
return 0;
}
?>`
lordfarquaad at notredomaine dot net
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.`
mina86 at tlen dot pl
17-Aug-2004 07:16
`A better (faster) version:
<?php
function in_array ($item, $array) {
$item = &strtoupper($item);
foreach($array as $element) {
if ($item == strtoupper($element)) {
return true;
}
}
return false;
}
?>
Noah B, set the 3rd argument to true and everything will wokr fine :) 0 == 'foo' is true, however 0 === 'foo' is not.`
php at NOSPAM dot fastercat dot com
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.`
fierojoe at fierojoe dot com
23-Mar-2004 01:03
`I couldn't find an easy way to search an array of associative arrays and return the key of the found associative array, so I created this little function to do it for me. Very handy for searching through the results of a mysql_fetch_assoc()
<?php
$a = array(
array('id' => 1, 'name' => 'oranges'),
array('id' => 2, 'name' => 'apples'),
array('id' => 3, 'name' => 'coconuts'),
);
function _array_search($s, $a) {
for($i=0; $i <= count($a); $i++) {
if (in_array($s, $a[$i])) {
return($i);
break;
}
}
return(FALSE);
}
//returns key 0 for the second element, 'id' => 1
echo _array_search(1, $a);
//returns key 2 for the second element, 'id' => 3
echo _array_search(3, $a);
//returns key 1 for the second element, 'id' => 2
echo _array_search(2, $a);
?>`
zapher at cae dot hl2files dot com
25-Feb-2004 12:59
`I corrected one_eddie at tenbit dot pl 's case-insensitive-script... It kinda didn't work :p
function in_array_cin($strItem, $arItems)
{
$bFound = FALSE;
foreach ($arItems as $strValue)
{
if (strtoupper($strItem) == strtoupper($strValue))
{
$bFound = TRUE;
}
}
echo $bFound;
}`
sean at natoewal dot nl
20-Feb-2004 04:56
`For searching an object in array I made the ObjectArray class. An instance of this class is an array which contains the objects as strings which makes searching for objects possible.
<?php
class ObjectArray {
var $objectArray = array();
function ObjectArray() {
}
function inArray($object) {
$needle = $this->object2String($object);
return in_array($needle, $this->objectArray);
}
function object2String($object) {
$str = "";
$vars = get_object_vars($object);
foreach ($vars as $value)
$str .= (is_object($value)) ? $this->object2String($value) : $value;
return $str;
}
function addObject($object) {
$str = $this->object2String($object);
array_push($this->objectArray, $str);
}
}
?>
You can use this class like:
<?php
$objectArray = new ObjectArray();
$myFirstCar = new Car("brown", 20);
$objectArray->addObject($myFirstCar);
$mySecondCar = new Car("red", 160);
$objectArray->addObject($mySecondCar);
?>
This example uses the Car class:
<?php
class Car {
var $color;
var $speed;
function Car($color, $speed) {
$this->color = $color;
$this->speed = $speed;
}
}
?>
The next code shows an example if we were searching for my first car:
<?php
if ($objectArray->inArray($myFirstCar)) {
echo "I've found your first car!";
}
?>`
one_eddie at tenbit dot pl
09-Feb-2004 05:16
`I found no sample with case-insensitive in_array. Here's one i wrote:
function in_array_cin($strItem, $arItems)
{
$bFound = FALSE;
foreach ($arItems as str$Value)
{
if (strtpupper($strItem) == strtoupper($strValue))
$bFound = TRUE;
}
return $bFound;
}`
Frank Str�ter
14-Jan-2004 09:08
`I forgot ta add $value === $needle instead of $value == $needle. The first one does a strict check. Thanks to the note by michi I have reduced the function to:
<?php
function in_array_multi($needle, $haystack) {
if (!is_array($haystack)) return false;
while (list($key, $value) = each($haystack)) {
if (is_array($value) && in_array_multi($needle, $value) || $value === $needle) {
return true;
}
}
return false;
}
?>`
mark at x2software dot net
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...`
gphemsley at users dot sourceforge dot net
01-Jan-2004 11:18
`For those of you who need in_array() for PHP3, this function should do the trick.
<?php
function in_array( $needle, $haystack, $strict = FALSE )
{
@reset( $haystack );
while( @list( , $value ) = @each( $haystack ) )
{
if( $needle == $value )
{
if( $strict && ( gettype( $needle ) != gettype( $value ) ) )
{
return FALSE;
}
else
{
return TRUE;
}
}
}
return FALSE;
}
?>`
Lee Benson
07-Nov-2003 03:36
`If you're trying to compare a variable against several possible other variables, like this...
if ($var == 1 || $var == 2 || $var == 3 || $var == 4) {
// do this
}
You can make your code a lot neater by doing this:
if (in_array($var,array(1,2,3,4))) {
// do this
}
This way, you're not repeating the "$var == x ||" part of your expression over and over again.
If you've used MySQL's IN() function for searching on multiple values, you'll probably appreciate using this code in your PHP scripts.
Hope this helps a few people.`
michi at F*CKSPAM michianimations dot de
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";
?>`
jr at jrmanes dot com
31-Jul-2003 11:35
`/*
** A function that checks to see if a string in an array
** exists in a string.
** example:
** $string = "My name is J.R.";
** $array = array("Mike", "Joe", "Bob", "J.R.");
** if (arrayinstr($string, $array)) echo "Found it!";
*/
function arrayinstr($haystack, $needle) {
$foundit = false;
foreach($needle as $value) {
if (!strpos($haystack, $value) === false)
$foundit = true;
}
return $foundit;
}`
raphinou at yahoo dot Com
22-Mar-2003 03:45
`If the haystack contains the boolean true, in_array returns true!!
Check this (PHP 4.2.3-8 debian package) :
<?php
$r=array("fzsgsdgsd","reazrazr","rezarzearzae",true);
$ret=in_array("tsuser_id",$r);
print "<H1>__ $ret __</H1>";
}
?>`
greg at serberus dot co dot uk
01-Feb-2003 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);
}`
melissa at hotmail dot com
27-Dec-2002 12:53
`With a bit of testing I've found this function to be quite in-efficient...
To demonstrate... I tested 30000 lookups in a consistant environment. Using an internal stopwatch function I got approximate time of over 1.5 mins using the in_array function.
However, using an associative array this time was reduced to less than 1 second...
In short... Its probably not a good idea to use in_array on arrays bigger than a couple of thousand...
The growth is exponential...
values
in_array assocative array
1000 00:00.05 00:00.01
10000 00:08.30 00:00.06
30000 01:38.61 00:00.28
100000 ...(over 15mins).... 00:00.64
Example Code... test it out for yourself...:
//=============================================
$Count = 0;
$Blah = array();
while($Count<30000)
{
if(!$Blah[$Count])
$Blah[$Count]=1;
$Count++;
}
echo "Associative Array";
$Count = 0;
$Blah = array();
while($Count<30000)
{
if(!in_array($Count, $Blah))
$Blah[] = $Count;
$Count++;
}
echo "In_Array";
//=============================================`
pingjuNOSPAM at stud dot NOSPAM dot ntnu dot no
25-Nov-2002 06:56
`if the needle is only a part of an element in the haystack, FALSE will be returned, though the difference maybe only a special char like line feeding (\n or \r).`
bbisgod AT hotmail DOT com
01-Oct-2002 05:17
`I had a HUGE problem of comparing references to see if they were pointing to the same object.
I ended up using this code!
function in_o_array (&$needle, &$haystack) {
if (!is_array($haystack)) return false;
foreach ($haystack as $key => $val) {
if (check_refs($needle, $haystack[$key])) return true;
}
return false;
}
function check_refs(&$a, &$b) {
$tmp = uniqid("");
$a->$tmp = true;
$bResult = !empty($b->$tmp);
unset($a->$tmp);
return $bResult;
}
Hope this helps someone have a more productive morning that me! :P`
leighnus at mbox dot com dot au
21-Aug-2002 12:18
`Alternative method to find an array within an array (if your version of php doesn't support array type $needles):
function array_in_array($needle, $haystack) {
foreach ($haystack as $value) {
if ($needle == $value)
return true;
}
return false;
}`
tom at orbittechservices dot com
09-Aug-2002 07:17
`I searched the general mailing list and found that in PHP versions before 4.2.0 needle was not allowed to be an array.
Here's how I solved it to check if a value is in_array to avoid duplicates;
$myArray = array(array('p', 'h'), array('p', 'r'));
$newValue = "q";
$newInsert = array('p','q');
$itBeInThere = 0;
foreach ($myArray as $currentValue) {
if (in_array ($newValue, $currentValue)) {
$itBeInThere = 1;
}
if ($itBeInThere != 1) {
array_unshift ($myArray, $newInsert);
}`
robe_NO_SPAM at post_NO_SPAM dot cz
06-Aug-2002 03:32
`In contribution of <jon@gaarsmand.dk>:
I think we should use more general approach while walking through array, so instead your 'for' loop I'd suggest while list.. as follows:
function in_multi_array($needle, $haystack) //taken from php.net, adapted { $in_multi_array = false; if(in_array($needle, $haystack)) { $in_multi_array = true; } else { while (list($tmpkey,$tmpval) = each ($haystack)) //here is the change
{ if(is_array($haystack[$tmpkey])){ if (in_multi_array($needle, $haystack[$tmpkey])) { $in_multi_array = true; break; } } } } return $in_multi_array; }
I hope code is readible, some problems with formatting occured.`
nicolaszujev at hot dot ee
19-Jul-2002 09:40
`I wrote this function to check key in array and also check value if it exists...
function in_array_key($key, $array, $value = false)
{
while(list($k, $v) = each($array))
{
if($key == $k)
{
if($value && $value == $v)
return true;
elseif($value && $value != $v)
return false;
else
return true;
}
}
return false;
}
.. very helpful function ...`
01-Jul-2002 12:22
`Looking at in_array, and array_search, I made up this small little example that does exactly what _I_ want.
<?php
$online = array ("1337", "killer", "bob");
$find = array ("Damien", "bob", "fred", "1337");
while (list ($key, $val) = each ($find)) {
if (in_array ($val, $online)) {
echo $val . "<br>";
}
}
?>
Look for all instances of $find in $online. and print the element that was found.`
penneyda at hotmail dot com
25-Jun-2002 11:23
`If you are using in_array() to search through a file using the file() function, it seems you have to add the line break "\n". It took me forever to figure out what the deal was.
Example:
$new_array = file("testing.txt");
if(in_array("$word_one : $word_two\n", $new_array))
{
print("success");
exit;
}
else
{
print("failure");
exit;
}
I just started learning PHP, but let me know if I have not figured this out correctly`
one at groobo dot com
07-May-2002 03:14
`Sometimes, you might want to search values in array, that does not exist. In this case php will display nasty warning:
Wrong datatype for second argument in call to in_array() .
In this case, add a simple statement before the in_array function:
if (sizeof($arr_to_searchin) == 0 || !in_array($value, $arr_to_searchin)) { ... }
In this case, the 1st statement will return true, omitting the 2nd one.`
jon at gaarsmand dot dk
09-Apr-2002 08:53
`If you want to search a multiple array for a value - you can use this function - which looks up the value in any of the arrays dimensions (like in_array() does in the first dimension).
Note that the speed is growing proportional with the size of the array - why in_array is best if you can determine where to look for the value.
Copy & paste this into your code...
function in_multi_array($needle, $haystack)
{
$in_multi_array = false;
if(in_array($needle, $haystack))
{
$in_multi_array = true;
}
else
{
for($i = 0; $i < sizeof($haystack); $i++)
{
if(is_array($haystack[$i]))
{
if(in_multi_array($needle, $haystack[$i]))
{
$in_multi_array = true;
break;
}
}
}
}
return $in_multi_array;
}`
add a note
key extract

Last updated: Sat, 27 Jan 2007
show source | credits | stats | sitemap | contact | advertising | mirror sites
Copyright © 2001-2007 The PHP Group
All rights reserved.
This mirror generously provided by: Yahoo! Inc.
Last updated: Sat Mar 10 09:32:46 2007 PST