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;
}
?>
in_array
(PHP 4, PHP 5)
in_array — 配列に値があるかチェックする
説明
bool in_array
( mixed $needle
, array $haystack
[, bool $strict
] )
needle で haystack を検索し、配列にそれがあった場合に TRUE、それ以外の場合は、FALSE を返します。
三番目のパラメータ strict が TRUE に設定された場合、 in_array() は、haystack の中の needle の 型も確認します。
注意: needle が文字列の場合、 比較の際に大文字小文字は区別されます。
注意: PHP 4.2.0 以前では needle に配列を使用することはできませんでした。
Example#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
Example#2 strict を指定した in_array() の例
<?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";
}
?>
上の例の出力は以下となります。
1.13 found with strict check
Example#3 needleが配列の場合の in_array()
<?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";
}
?>
上の例の出力は以下となります。
'ph' was found 'o' was found
array_search()、 array_key_exists() および isset() も参照ください。
in_array
sick949 at hotmail dot com
05-Mar-2008 08:43
05-Mar-2008 08:43
ucffool
17-Feb-2008 04:51
17-Feb-2008 04:51
@vidmantas
I had different results... Here is an example:
<?php
$array = array();
for ($x=1;$x <= 1000;$x++):
$array[] = mt_rand(100000,999999);
endfor;
$value = 123456;
$time=microtime(1);
if (in_array($value,$array)):
echo "Found! ";
else:
echo "Not found! ";
endif;
$time=number_format(microtime(1)-$time, 6);
echo "Time to complete: " . $time;
echo "<br />"; // -------------------------------------
$time=microtime(1);
$array2 = array_flip($array);
if (isset($array2[$value])):
echo "Found! ";
else:
echo "Not found! ";
endif;
$time=number_format(microtime(1)-$time, 6);
echo "Time to complete: " . $time;
?>
RESULT:
Not found! Time to complete: 0.000075
Not found! Time to complete: 0.000259
So I would say that on PHP5 at least, in_array seems to be more effective.
vidmantas dot norkus at neo dot lt
13-Feb-2008 02:16
13-Feb-2008 02:16
Speed test on frequent search in array
<?php
//timer class
// php 4+
class WDM_Timer{
var $start;
function WDM_Timer(){
$this->start=$this->microtime_float();
}
function microtime_float(){
list($usec, $sec) = explode(" ", microtime());
return (float)$usec + (float)$sec;
}
function stop($precision=2){
$precision=(int)$precision;
return sprintf("%01.{$precision}f",$this-> microtime_float() - (float)$this->start);
}
}
//lets generate array
$ARR1=Array();
for($i=0;$i<10000;$i++){
$key=rand(100000000000000000, 1000000000000000000);
$ARR1[]=$key;
}
///==================================START TEST 1
$timer=new WDM_Timer();
foreach($ARR1 as $key => $val)
in_array($key,$ARR1);
echo "TEST1 in_array(\$key,\$ARR) SEARCH. TIME ELAPSED: ".$timer->stop(10)."\n";
///==================================PREPARE TEST 2
//lets flip array, you can use $ARR2=array_flip($ARR1);
$ARR2=Array();
foreach($ARR1 as $key => $val)
$ARR2[$val]='';
//==================================START TEST2
$timer=new WDM_Timer();
foreach($ARR2 as $key => $val)
isset($ARR[$key]);
echo "TEST2 isset(\$ARR[\$key]) SEARCH. TIME ELAPSED: ".$timer->stop(10)."\n";
?>
test results on my server:
TEST1 in_array($key,$ARR) SEARCH. TIME ELAPSED: 8.5608828068
TEST2 isset($ARR[$key]) SEARCH. TIME ELAPSED: 0.0020029545
anonymous at vitut dot us
12-Feb-2008 11:55
12-Feb-2008 11:55
in_array is pretty slow on big arrays, I used isset() instead in one of my projects. It works well if you are building the array yourself.
old way...
// build some array
while (something)
$array[] = $value;
// use it to check something
if (in_array($search, $array)) {
// something...
}
better way...
// build some array
while (something)
$array[$value] = true;
// use it to check something
if (isset($array[$search])) {
// something...
}
if you are using something like this, the improvement in speed is immense when using isset() instead of in_array()
guitar king
30-Jan-2008 04:52
30-Jan-2008 04:52
In PHP 4, the first argument seems not allowed to be an object. In PHP 5, also objects are allowed as $needle.
lakinekaki at gmail dot com
05-Jan-2008 05:01
05-Jan-2008 05:01
Breadcrumbs navigation for small sites with flat directory structure
Page levels are defined in a multidimensional array. Example array given below
<?php
$array = array(
"contact",
"projects" ,
"projects" => array("architecture",
"architecture" => array("flats","malls")),
"hobbies"
);
function recursive_path($needle,$haystack,$current=''){
if(!is_array($haystack)) return '';
$ret='';
$csad = "$current > <b>$needle</b>";
if(in_array($needle,$haystack))return $csad;
else{
foreach($haystack as $key => $element){
$cposle = "$current > <a href=\"$key.html\">$key</a>";$ret .= recursive_path($needle,$element,$cposle);
}
}
return $ret;
}
// if current filename is needle, and site structure haystack, than this prints navigation path
echo recursive_path($filename,$array,'You are here: <a href="./">home</a>');
?>
I tried to do this without redundancies, but after many wasted hours, had to place 'duplicate' values for 'node' keys.
Suggestion for editors:
I was always impressed with this manual, and find it better than any other online programming resource. I wanted to find out more about the editing process behind it, and I discovered this:
http://news.php.net/php.notes/start/150000
Spending some time there, I saw quite a few useful scripts, and am therefore confused by their deletions. I can only assume that your level of knowledge is so far beyond of us regular PHP users, and to you most of scripts are obvious, that to us took a while to write.
Anyhow, here is suggestion: Since you already have almost dozen categories for managing notes, couldn't you send emails to authors informing them which decision was made. It would be informative and useful to do that. After all, if 'error' in the editing process is only 3%, it still results in almost 3000 very good notes deleted!
Thanks
f d0t fesser att gmx d0t net
16-Oct-2007 07:20
16-Oct-2007 07:20
In case you have to check for unknown or dynamic variables in an array, you can use the following simple work-around to avoid misleading checks against empty and zero values (and only these "values"!):
<?php
in_array($value, $my_array, empty($value) && $value !== '0');
?>
The function empty() is the right choice as it turns to true for all 0, null and ''.
The '0' value (where empty() returns true as well) has to be excluded manually (as this is handled by in_array correctly!).
Examples:
<?php
$val = 0;
$res = in_array($val, array('2007'));
?>
leads incorrectly to true where
<?php
$val = 0;
$res = in_array($val, array('2007'), empty($val) && $val !== '0');
?>
leads correctly to false (strict check!) while
<?php
$val = 2007;
$res = in_array($val, array('2007'), empty($val) && $val !== '0');
?>
still correctly finds the '2007' ($res === true) because it ignores strict checking for that value.
info at b1g dot de
03-Aug-2007 02:44
03-Aug-2007 02:44
Be careful with checking for "zero" in arrays when you are not in strict mode.
in_array(0, array()) == true
in_array(0, array(), true) == false
Quaquaversal
21-May-2007 12:48
21-May-2007 12:48
A simple function to type less when wanting to check if any one of many values is in a single array.
<?php
function array_in_array($needle, $haystack) {
//Make sure $needle is an array for foreach
if(!is_array($needle)) $needle = array($needle);
//For each value in $needle, return TRUE if in $haystack
foreach($needle as $pin)
if(in_array($pin, $haystack)) return TRUE;
//Return FALSE if none of the values from $needle are found in $haystack
return FALSE;
}
?>
Bodo Graumann
17-Mar-2007 03:43
17-Mar-2007 03:43
Be careful!
in_array(null, $some_array)
seems to differ between versions
with 5.1.2 it is false
but with 5.2.1 it's true!
ben
27-Feb-2007 06:25
27-Feb-2007 06: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 06:11
12-Feb-2007 06:11
@vandor at ahimsa dot hu
Why first check normal and then strict, make it more dynamically??
<?php
function in_arrayr($needle, $haystack, strict = false) {
if($strict === false){
foreach ($haystack as $v) {
if ($needle == $v) return true;
elseif (is_array($v))
if (in_arrayr($needle, $v) == true) return true;
}
return false;
} else {
foreach ($haystack as $v) {
if ($needle === $v) return true;
elseif (is_array($v))
if (in_arrayr($needle, $v) === true) return true;
}
return false;
}
?>
mattsch at gmail dot com
27-Oct-2006 01:04
27-Oct-2006 01:04
I'm not sure why you would do a loop for a function that needs to be fast. There's an easier way:
function preg_array($strPattern, $arrInput){
$arrReturn = preg_grep($strPattern, $arrInput);
return (count($arrReturn)) ? true : false;
}
musik at krapplack dot de
04-Jun-2006 09:52
04-Jun-2006 09: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
09-Apr-2006 12:23
09-Apr-2006 12:23
Here's another deep_in_array function, but this one has a case-insensitive option :)
<?
function deep_in_array($value, $array, $case_insensitive = false){
foreach($array as $item){
if(is_array($item)) $ret = deep_in_array($value, $item, $case_insensitive);
else $ret = ($case_insensitive) ? strtolower($item)==$value : $item==$value;
if($ret)return $ret;
}
return false;
}
?>
contact at simplerezo dot com
25-Feb-2006 01:06
25-Feb-2006 01: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
23-Feb-2006 12:11
23-Feb-2006 12:11
Sorry, that deep_in_array() was a bit broken.
<?
function deep_in_array($value, $array) {
foreach($array as $item) {
if(!is_array($item)) {
if ($item == $value) return true;
else continue;
}
if(in_array($value, $item)) return true;
else if(deep_in_array($value, $item)) return true;
}
return false;
}
?>
kitchin
05-Feb-2006 11:52
05-Feb-2006 11: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.
14-Jan-2006 02: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
11-Jan-2006 12:18
11-Jan-2006 12: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
26-Nov-2005 07:59
26-Nov-2005 07: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 06:21
08-Nov-2005 06:21
hope this function may be useful to you, it checks an array recursively (if an array has sub-array-levels) and also the keys, if wanted:
<?php
function rec_in_array($needle, $haystack, $alsokeys=false)
{
if(!is_array($haystack)) return false;
if(in_array($needle, $haystack) || ($alsokeys && in_array($needle, array_keys($haystack)) )) return true;
else {
foreach($haystack AS $element) {
$ret = rec_in_array($needle, $element, $alsokeys);
}
}
return $ret;
}
?>
tacone at gmx dot net
03-Aug-2005 11:05
03-Aug-2005 11: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
12-Jul-2005 01:42
12-Jul-2005 01:42
Actually, that should be
<?PHP
function in_multi_array($needle, $haystack) {
$in_multi_array = false;
if(in_array($needle, $haystack)) {
$in_multi_array = true;
} else {
foreach ($haystack as $key => $val) {
if(is_array($val)) {
if(in_multi_array($needle, $val)) {
$in_multi_array = true;
break;
}
}
}
}
return $in_multi_array;
}
?>
Aragorn5551 at gmx dot de
11-Jun-2005 09:26
11-Jun-2005 09: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 09:49
17-May-2005 09: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 11:50
13-May-2005 11:50
in_array() doesn't seem to scale very well when the array you are searching becomes large. I often need to use in_array() when building an array of distinct values. The code below seems to scale better (even with the array_flip):
$distinct_words = array();
foreach ($article as $word) {
$flipped = array_flip($distinct_words);
if (!isset($flipped[$word]))
$distinct_words[] = $word;
}
This only works with arrays that have unique values.
lordfarquaad at notredomaine dot net
10-Sep-2004 11:44
10-Sep-2004 11: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 11:49
09-Sep-2004 11:49
Here is a function to search a string in multidimensional Arrays(you can have so much dimensions as you like:
function in_array_multi($needle, $haystack)
{
$found = false;
foreach($haystack as $value) if((is_array($value) && in_array_multi($needle, $value)) || $value == $needle) $found = true;
return $found;
}
It is a little shorter than the other function.
php at NOSPAM dot fastercat dot com
25-Apr-2004 06:54
25-Apr-2004 06:54
The description of in_array() is a little misleading. If needle is an array, in_array() and array_search() do not search in haystack for the _values_ contained in needle, but rather the array needle as a whole.
$needle = array(1234, 5678, 3829);
$haystack = array(3829, 20932, 1234);
in_array($needle, $haystack);
--> returns false because the array $needle is not present in $haystack.
Often people suggest looping through the array $needle and using in_array on each element, but in many situations you can use array_intersect() to get the same effect (as noted by others on the array_intersect() page):
array_intersect($needle, $haystack);
--> returns array(1234). It would return an empty array if none of the values in $needle were present in $haystack. This works with associative arrays as well.
mark at x2software dot net
10-Jan-2004 03:11
10-Jan-2004 03:11
Reply/addition to melissa at hotmail dot com's note about in_array being much slower than using a key approach: associative arrays (and presumably normal arrays as well) are hashes, their keys are indexed for fast lookups as the test showed. It is often a good idea to build lookup tables this way if you need to do many searches in an array...
For example, I had to do case-insensitive searches. Instead of using the preg_grep approach described below I created a second array with lowercase keys using this simple function:
<?php
/**
* Generates a lower-case lookup table
*
* @param array $array the array
* @return array an associative array with the keys being equal
* to the value in lower-case
*/
function LowerKeyArray($array)
{
$result = array();
reset($array);
while (list($index, $value) = each($array))
{
$result[strtolower($value)] = $value;
}
return $result;
}
?>
Using $lookup[strtolower($whatyouneedtofind)] you can easily get the original value (and check if it exists using isset()) without looping through the array every time...
michi at F*CKSPAM michianimations dot de
27-Oct-2003 09:47
27-Oct-2003 09: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
13-Aug-2003 02:00
13-Aug-2003 02:00
either the benchmark I used, or the one used in an earlier comment is flawed, or this function has seen great improvement...
on my system (a Duron 1GHz box) the following benchmark script gave me pretty close to
1 second execution time average when used with 355000 runs of in_array() (10 runs)
<?php
$average = 0;
for ($run=0;$run<10;++$run) {
$test_with=array(
1=>array(explode(":",
":1:2:3:4:5:6:7:8:9:10:11:12:13:14:15:")),
2=>array(explode(":",
":21:22:23:24:25:26:27:28:29:210:211:212:213:214:215:")),
3=>array(explode(":",
":14:15:23:24:25:26:27:28:29:210:211:212:213:214:215:"))
);
$start = microtime();
for($i=0;$i<=355000;++$i) { in_array($i, $test_with); }
$end = microtime();
$start = explode(" ",$start);
$end = explode(" ",$end);
$start = $start[1].trim($start[0],'0');
$end = $end[1].trim($end[0],'0');
$time = $end - $start;
$average += $time;
echo "run $run: $time<br>";
}
$average /= 10;
echo "average: $average";
?>
greg at serberus dot co dot uk
01-Feb-2003 09:48
01-Feb-2003 09: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
08-Jan-2003 10:05
08-Jan-2003 10: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 05:53
27-Dec-2002 05: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 11:56
25-Nov-2002 11: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).
tom at orbittechservices dot com
10-Aug-2002 11:17
10-Aug-2002 11: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);
}
one at groobo dot com
08-May-2002 07:14
08-May-2002 07: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
10-Apr-2002 12:53
10-Apr-2002 12: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;
}