Well, ok - it's really not that fast when you test case-insensitive. but its ok.
i use it for spider/bot identification. as you can imagine there are a lot of useragents to check for in the database after some time.
-this is <vandor at ahimsa dot hu>'s function a lil bit extendet. (senseless? maybe...)
function is_in_array($needle, $haystack, $case_sensitive=true)
{
if($case_sensitive===false)
$needle=strtolower($needle);
foreach($haystack as $v)
{
if(!is_array($v))
{
if(!$case_sensitive)
$v=strtolower($v);
if($needle == $v)
return true;
}
else
{
if(is_in_array($needle, $v, $case_sensitive) === true)
return true;
}
}
return false;
}
in_array
(PHP 4, PHP 5)
in_array — Prüft, ob ein Wert in einem Array existiert
Beschreibung
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
needleein String so wird bei der Suche Groß- und Kleinschreibung beachtet. -
haystack -
Das zu durchsuchende Array.
-
strict -
Wenn der dritte Parameter auf
TRUEgesetzt wird vergleicht in_array() nicht nur den Wert sondern auch den Typ des gesuchten Wertesneedlemit 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.4, 1.13);
if (in_array('12.4', $a, true)) {
echo "'12.4' bei strenger Prüfung gefunden\n";
}
if (in_array(1.13, $a, true)) {
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
in_array
08-Jun-2007 01:00
07-Jun-2007 11:40
RE: In trying to emulate a case insensitive in_array()....
why not :
foreach the parameter vals, strtolower them
and after that have a small and simple in_array functioncall ... ?
should be mouch smarter ;)
02-Jun-2007 10:54
If you ever need to print out an table of 2-dimensional array, here is one I made:
<?php
function MakeTableOf2DArray($db)
{
$col_cnt=0; $row_cnt=0;
$col = array(); $row = array();
foreach ($db as $key => $val)
{
if (! in_array($key,$col,true))
{
$col[$col_cnt] = $key;
$col_cnt++;
}
foreach ($val as $skey => $sval)
{
if (! in_array($skey,$row,true))
{
$row[$row_cnt] = $skey;
$row_cnt++;
}
}
}
$res = '<table><tr><td width="100">'.$col[$i].'</td>';
for ($i=0;$i<$col_cnt;$i++)
{
$res .= '<td width="100">'.$col[$i].'</td>';
}
$res .= '</tr>'."\n";
for ($i=0;$i<$row_cnt;$i++)
{
$res .= '<tr>';
$res .= '<td>'.$row[$i].'</td>';
for ($o=0;$o<$col_cnt;$o++)
{
$res .= '<td>'. (isset($db[$col[$o]][$row[$i]])? $db[$col[$o]][$row[$i]]: ' ').'</td>';
}
$res .= '</tr>'."\n";
}
$res .= '</table>';
return $res;
}
//example
$db = Array
(
'ab' => Array
(
'janik' => 1 ,
'vendula' => 3 ,
'eva' => 5
) ,
'lg' => Array
(
'janik' => 4 ,
'eva' => 2 ,
'misa' => 6
)
);
echo MakeTableOf2DArray($db);
?>
prints out:
| | ab | lg |
| janik | 1 | 4 |
| vendula | 3 | |
| eva | 5 | 2 |
| misa | | 6 |
22-May-2007 10:22
@mike at php-webdesign dot nl
will not work as desired if you don't check for strict in the recurssion
21-May-2007 05: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;
}
?>
16-Mar-2007 07: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!
27-Feb-2007 10: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.
12-Feb-2007 10: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;
}
?>
05-Jan-2007 12: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;
}
?>
29-Nov-2006 02: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.
27-Nov-2006 05: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.
26-Oct-2006 06: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;
}
17-Sep-2006 03: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;
}
}
?>
17-Jul-2006 05: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!";
}
?>
04-Jun-2006 02: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
09-Apr-2006 05: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;
}
?>
04-Apr-2006 11: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.
25-Feb-2006 05: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;
}
22-Feb-2006 04: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;
}
?>
18-Feb-2006 02: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;
}
05-Feb-2006 03: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.
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
?>
11-Jan-2006 04: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)
25-Nov-2005 11: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;
}
08-Nov-2005 10: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;
}
?>
01-Nov-2005 12: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
25-Oct-2005 02: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';
}
?>
20-Oct-2005 11: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;
}
?>
23-Sep-2005 04: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;
}
?>
03-Aug-2005 04: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]);
}
}
?>
11-Jul-2005 06: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;
}
?>
01-Jul-2005 02: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)
?>
30-Jun-2005 06: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])
11-Jun-2005 02: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.
17-May-2005 02: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);
13-May-2005 04: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.
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
07-Mar-2005 11: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.
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.
17-Nov-2004 04: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.
04-Nov-2004 11: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;
}
?>
10-Sep-2004 04: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;
}
?>
09-Sep-2004 04: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.
17-Aug-2004 04: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.
24-Apr-2004 11: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.
23-Mar-2004 10: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);
?>
25-Feb-2004 09: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;
}
21-Feb-2004 01: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!";
}
?>
10-Feb-2004 02: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;
}
14-Jan-2004 06: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;
}
?>
09-Jan-2004 07: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...
02-Jan-2004 08: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;
}
?>
08-Nov-2003 12: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.
27-Oct-2003 01: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;
}
12-Aug-2003 07: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";
?>
31-Jul-2003 08: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;
}
23-Mar-2003 12: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>";
}
?>
01-Feb-2003 01: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;
}
08-Jan-2003 02:05
case-insensitive version of in_array:
function is_in_array($str, $array) {
return preg_grep('/^' . preg_quote($str, '/') . '$/i', $array);
}
27-Dec-2002 09: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";
//=============================================
25-Nov-2002 03: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).
01-Oct-2002 02: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
21-Aug-2002 09: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;
}
10-Aug-2002 04: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);
}
06-Aug-2002 12: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.
19-Jul-2002 06: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 ...
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.
25-Jun-2002 08: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
08-May-2002 12: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.
09-Apr-2002 05: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;
}