A notice to the, by alishanovin [at] hotmail. [dot] com released, in_array wrapper function:
You should use Pre-Increment, e.g. instead of "$i++" -> "++$i".
Pre-Incrementing is prooved to be 10 % faster, which makes a search-trip in a Thousand-Dimension-Array a quite faster.
Changed Version:
<?php
function in_wildarray($needle, $haystack, $case_sensitive=true) {
$is_wild = (!strpos($needle,"*")) ? false : true;
$needles = ($is_wild) ? explode("*", $needle) : array();
$needle = ($case_sensitive) ? $needle : strtolower($needle);
for($i=0, $req = count($haystack);$i < $req; ++$i) {
$haystack_str = ($case_sensitive) ? $haystack[$i] : strtolower($haystack[$i]);
if ($is_wild) {
$found = false;
for($x=0, $req = count($needles); $x < $req;++$x) {
$needle_index = strpos($haystack_str, trim($needles['x']));
$found = (!$needle_index) ? false : ($haystack_str = substr($haystack_str, 0, $needle_index ? true : false));
}
if ($found) return true;
} elseif (!$is_wild && $haystack_str == $needle) {
return true;
}
}
return false;
}
?>
--
Kenan Sulayman
Application Designer,
KurealCorporation inc.
in_array
(PHP 4, PHP 5)
in_array — Checks if a value exists in an array
Description
Searches haystack for needle .
Parameters
- needle
-
The searched value.
Note: If needle is a string, the comparison is done in a case-sensitive manner.
- haystack
-
The array.
- strict
-
If the third parameter strict is set to TRUE then the in_array() function will also check the types of the needle in the haystack .
Return Values
Returns TRUE if needle is found in the array, FALSE otherwise.
ChangeLog
| Version | Description |
|---|---|
| 4.2.0 | needle may now be an array. |
Examples
Example #1 in_array() example
<?php
$os = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $os)) {
echo "Got Irix";
}
if (in_array("mac", $os)) {
echo "Got mac";
}
?>
The second condition fails because in_array() is case-sensitive, so the program above will display:
Got Irix
Example #2 in_array() with strict example
<?php
$a = array('1.10', 12.4, 1.13);
if (in_array('12.4', $a, true)) {
echo "'12.4' found with strict check\n";
}
if (in_array(1.13, $a, true)) {
echo "1.13 found with strict check\n";
}
?>
The above example will output:
1.13 found with strict check
Example #3 in_array() with an array as needle
<?php
$a = array(array('p', 'h'), array('p', 'r'), 'o');
if (in_array(array('p', 'h'), $a)) {
echo "'ph' was found\n";
}
if (in_array(array('f', 'i'), $a)) {
echo "'fi' was found\n";
}
if (in_array('o', $a)) {
echo "'o' was found\n";
}
?>
The above example will output:
'ph' was found 'o' was found
in_array
18-Sep-2008 09:46
16-Sep-2008 11:54
Small method i built for my Array module, after looking through the manual I wanted a small compact way of making a wildcard search through an arrays values, and returning only those that it found.
<?php
/**
* Takes a needle and haystack (just like in_array()) and does a wildcard search on it's values.
*
* @param string $string Needle to find
* @param array $array Haystack to look through
* @result array Returns the elements that the $string was found in
*/
function find ($string, $array = array ())
{
foreach ($array as $key => $value) {
unset ($array[$key]);
if (strpos($value, $string) !== false) {
$array[$key] = $value;
}
}
return $array;
}
?>
04-Sep-2008 09:33
Just caught a small bug in my code below...
As the code is right now, when there are wild cards, it will treat the initial segment as though it's preceded with a wild card. In other words, the first segment will be searched, not simply at the beginning of the string, but anywhere. Because it's a simple fix, I'll leave it to others. :)
02-Sep-2008 09:43
Here's a function that does an in_array, but takes wildcards in the needle, and also can be case sensitive/insensitive...
A few points:
-It doesn't use foreach, but for, which is quicker
-I didn't use regex to search with a wildcard for the reason that the needle could be unpredictable if it's user-input, and rather than having to escape metacharacters, I decided it would be easier to do a plain text comparison.
-Needles with wildcards can come in many forms such as:
Str*ng
S*r*ng*
*rng
*i*n*
so a split is being done on that string, and each part is then compared with the current item. If the first part is not found, the comparison is done, and we move on. If it IS found, we move on to the next part of the needle, while chopping off the initial part of the haystack string. This is to ensure that each comparison of a needle part is looking at the next part of the haystack string.
For example:
needle: "Bo*bo"
haystack[0] = "Bob is lazy"
On the first pass, when searching "Bo", we then modify the haystack[0] to be: "b is lazy" so that "bo" is compared with that. Otherwise, we'd be comparing "bo" with "Bob is lazy", and returning true incorrectly.
I haven't fully tested the function, so let me know if you spot any bugs, or have any questions.
<?php
function in_wildarray($needle, $haystack, $case_sensitive=true) {
$is_wild = (strpos($needle,"*")===true)? true : false;
$needles = ($is_wild)? explode("*", $needle) : array();
$needle = ($case_sensitive)? $needle : strtolower($needle);
for($i=0;$i<count($haystack);$i++) {
$haystack_str = ($case_sensitive)? haystack[$i] : strtolower($haystack[$i]);
if ($is_wild) {
$found = false;
for($x=0;$x<count($needles);$x++) {
$needle_part = trim($needles[x]);
$needle_index = strpos($haystack_str, $needle_part);
if ($needle_index===false) {
$found = false;
break; //break out of the loop, because string part is not found in the haystack string
} else {
$found = true;
//chop off the start of the string to the needle_index
//so we can be sure that the found items are in the correct order
//and we are avoiding the potential of finding duplicate characters
$haystack_str = substr($haystack_str, 0, $needle_index);
}
}
if ($found) { return true; }
} elseif (!$is_wild && $haystack_str == $needle) {
return true;
}
}
return false;
}
?>
29-Aug-2008 11:04
Maybe the most efficient recursive in_array variation yet? ;)
<?php
function recursive_in_array($needle, $haystack) {
foreach ($haystack as $stalk) {
if ($needle == $stalk || (is_array($stalk) && recursive_in_array($needle, $stalk))) {
return true;
}
}
return false;
}
?>
29-Aug-2008 09:32
This is another implementation of the in_arrayr() function found further down below which didn't really work (it returned upon finding the first nested array and ignoring all other nested arrays).
<?php
function in_arrayr($needle, $haystack, &$found = false) {
foreach ($haystack as $v) {
if ($needle == $v) {
$found = true;
return true;
} elseif (is_array($v)) {
$this->in_arrayr($needle, $v, $found);
}
}
return $found;
}
?>
22-Jul-2008 07:58
@param mixed $key (string || array)
<?php
function inArray($array, $key)
{
if(func_num_args() == 2 && is_string($key))
return in_array($key, $array);
else if(func_num_args() == 2 && is_array($key))
{
$r = true;
for($i=0; $i < count($key); $i++)
$r = (!in_array($key[$i], $array)) ? false : $r;
return $r;
}
else if(func_num_args > 2)
{
$args = func_get_args();
$r = true;
for($i=1; $i < count($args); $i++)
$r = (!in_array($args[$i], $array)) ? false : $r;
return $r;
}
}
/* EXAMPLES */
$array = array('a', 'b', 'c', 'd', 'e', 'f');
// Example 1
if(inArray($array, 'b'))
echo 'b is in array';
// Example 2
if(inArray($array, array('b', 'a', 'e')))
echo 'a, b and e are in array';
// Example 3
if(inArray($array, 'b', 'a', 'e'))
echo 'a, b and e are in array';
?>
21-Jul-2008 05:34
Recursive in array using SPL
<?php
function in_array_recursive($needle, $haystack) {
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($haystack));
foreach($it AS $element) {
if($element == $needle) {
return true;
}
}
return false;
}
?>
12-Jul-2008 12:47
function to check a multidimensional array if a given array is in the "haystack".
<?
$Example_Needle['Art'] = 'Verb';
$Example_Needle['Verbform']['Finitiv'] = 1;
$Example_Haystack[5] = 2;
$Example_Haystack[7] = 'nein';
$Example_Haystack['ID'] = 1;
$Example_Haystack['Art'] = 'Verb';
$Example_Haystack['Verbform']['Finitiv'] = 1;
$Example_Haystack['Zeitform']['Präsens'] = 'ja';
function is_in_array($Needle, $Haystack){
reset($Needle);
while(list($Key, $Value) = each($Needle)){
if(!array_key_exists($Key, $Haystack)){
return false;
}
if(!is_array($Value)){
if(in_array($Value, $Haystack)){
$Return = true;
}else{
return false;
}
}else{
if(is_in_array($Value, $Haystack[$Key])){
$Return = true;
}else{
return false;
}
}
}
return $Return;
}
if(is_in_array($Example_Needle, $Example_Haystack)){
echo 'yes';
}else{
echo 'no';
}
?>
This will emit "yes". The given needle must be an array. A string as the needle is not supported in this function.
27-Jun-2008 11:20
Improved (in readability, anyhow) multi-array search:
<?
// Function for looking for a value in a multi-dimensional array
function in_multi_array($value, $array)
{
foreach ($array as $key => $item)
{
// Item is not an array
if (!is_array($item))
{
// Is this item our value?
if ($item == $value) return true;
}
// Item is an array
else
{
// See if the array name matches our value
//if ($key == $value) return true;
// See if this array matches our value
if (in_array($value, $item)) return true;
// Search this array
else if (in_multi_array($value, $item)) return true;
}
}
// Couldn't find the value in array
return false;
}
?>
If you want the function to also match keys (such as if you are searching for an array called 'apple' inside of an array), uncomment this line:
<?
//if ($key == $value) return true;
?>
07-Jun-2008 09:01
<?php
$pages = array('help', 'main', 'contact');
function isDefined($page) {
return in_array($page, $pages, true);
}
$act = $_GET['act'];
function loadPage() {
if(isDefined($act))
include $act . '.php';
else
include 'index.php';
}
loadPage();
?>
Just wrote it so I could load pages, and if they're not defined in the array, I can load the default page.
20-May-2008 04:05
@Martijn Wieringa
read about the strict parameter.
<?php
var_dump( in_array(0, array(42), true) );
var_dump( in_array(0, array('42'), true) );
var_dump( in_array(0, array('Foo'), true) );
var_dump( in_array('0', array('Foo'), true) );
var_dump( in_array('0', array(0), true) );
var_dump( in_array('0', array('0'), true) );
?>
19-May-2008 11:20
When using numbers as needle, it gets tricky:
Note this behaviour (3rd statement):
in_array(0, array(42)) = FALSE
in_array(0, array('42')) = FALSE
in_array(0, array('Foo')) = TRUE
in_array('0', array('Foo')) = FALSE
09-Apr-2008 02:18
ucffool, in your code you calculate the time for array_flip with isset. This is why isset time is bigger than in_array.
simply replace
$time=microtime(1);
$array2 = array_flip($array);
with
$array2 = array_flip($array);
$time=microtime(1);
to get isset's real time.
09-Apr-2008 12:38
@mikegioia
And don't forget, that isset() looks for keys in arrays and in_array() looks for values. This could make also a significant difference in benchmarks, because the functions work in different ways.
06-Apr-2008 01:47
@rick (april 2006)
What is the point of making it case-insensitive and not using strtolower on both values? Fixed :)
<?php
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)==strtolower($value) : $item==$value;
if($ret)
return $ret;
}
return false;
}
?>
03-Apr-2008 04:06
<?php
function in_array_r($needle, $haystack)
{
$result = in_array($needle, $haystack);
if ($result) return $result;
foreach ($haystack as $v) {
if (is_array($v)) {
$result = in_array_r($needle, $v);
}
if ($result) return $result;
}
return $result;
}
?>
20-Mar-2008 08:49
@ vidmantas and ucffool:
There's a large difference between your methods of speed comparison. vidmantas is running in_array() and isset() in a for loop (once for each element of that large array) while ucffool just runs the functions.
I ran both speed tests and in_array() outperformed isset() every time.
05-Mar-2008 12:43
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;
}
?>
17-Feb-2008 08: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.
12-Feb-2008 06: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
12-Feb-2008 03: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()
29-Jan-2008 08:52
In PHP 4, the first argument seems not allowed to be an object. In PHP 5, also objects are allowed as $needle.
05-Jan-2008 09: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
16-Oct-2007 12: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.
02-Aug-2007 07: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
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;
}
?>
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;
}
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;
}
?>
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;
}
?>
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;
}
?>
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;
}
?>
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.
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.
