PHP 7.0.6 Released

User Contributed Notes

xfoxawy at gmail dot com
1 year ago
in (PHP 5 >= 5.5.0) you don't have to write your own function to search through a multi dimensional array

ex :

$userdb=Array
(
    (0) => Array
        (
            (uid) => '100',
            (name) => 'Sandra Shush',
            (url) => 'urlof100'
        ),

    (1) => Array
        (
            (uid) => '5465',
            (name) => 'Stefanie Mcmohn',
            (pic_square) => 'urlof100'
        ),

    (2) => Array
        (
            (uid) => '40489',
            (name) => 'Michael',
            (pic_square) => 'urlof40489'
        )
);

simply u can use this

$key = array_search(40489, array_column($userdb, 'uid'));
maciej at speccode dot com
8 months ago
FYI, remember that strict mode is something that might save you hours.

If you're searching for a string and you have a "true" boolean on the way - you will get it as result (first occurrence). Example below:

<?php

$arr
= [
   
'foo'    => 'bar',
   
'abc'    => 'def',
   
'bool'   => true,
   
'target' => 'xyz'
];

var_dump( array_search( 'xyz', $arr ) ); //bool
var_dump( array_search( 'xyz', $arr, true ) ); //target

?>
buddel
6 years ago
the recursive function by tony have a small bug. it failes when a key is 0

here is the corrected version of this helpful function:

<?php
function recursive_array_search($needle,$haystack) {
    foreach(
$haystack as $key=>$value) {
       
$current_key=$key;
        if(
$needle===$value OR (is_array($value) && recursive_array_search($needle,$value) !== false)) {
            return
$current_key;
        }
    }
    return
false;
}
?>
stefano@takys dot it
5 years ago
for searching case insensitive better this:

<?php
array_search
(strtolower($element),array_map('strtolower',$array));
?>
revoke
4 years ago
Better solution of multidimensional searching.

<?php
function multidimensional_search($parents, $searched) {
  if (empty(
$searched) || empty($parents)) {
    return
false;
  }

  foreach (
$parents as $key => $value) {
   
$exists = true;
    foreach (
$searched as $skey => $svalue) {
     
$exists = ($exists && IsSet($parents[$key][$skey]) && $parents[$key][$skey] == $svalue);
    }
    if(
$exists){ return $key; }
  }

  return
false;
}

$parents = array();
$parents[] = array('date'=>1320883200, 'uid'=>3);
$parents[] = array('date'=>1320883200, 'uid'=>5);
$parents[] = array('date'=>1318204800, 'uid'=>5);

echo
multidimensional_search($parents, array('date'=>1320883200, 'uid'=>5)); // 1
?>
hyder7nh at gmail dot com
4 months ago
When using array_search in if statements with array elements that use integers for keys, if the key [0] matches, the statement would always return false.

This is because array_search returns the key of the value that matches with the first argument. If statements check if the return value is true or false(boolean), 0 is boolean for false.

This problem shouldn't occur with key names that are strings.

<?php

//$f would be 0, because key [0] matches the first argument
$f = array_search('photo', array('photo', 'audio'));

//$f statement would fall to else condition because $f is 0 and 0 is false
if($f==true)
{
    echo
'found<br/>';
}
else
{
    echo
'not found<br/>';
}

if(
array_search('photo', array('photo')))
{
    echo
'FOUND';
}
else
{
    echo
'NOT FOUND';
}

Use
the === operator to get around this problem.
cue at openxbox dot com
12 years ago
If you are using the result of array_search in a condition statement, make sure you use the === operator instead of == to test whether or not it found a match.  Otherwise, searching through an array with numeric indicies will result in index 0 always getting evaluated as false/null.  This nuance cost me a lot of time and sanity, so I hope this helps someone.  In case you don't know what I'm talking about, here's an example:

<?php
$code
= array("a", "b", "a", "c", "a", "b", "b"); // infamous abacabb mortal kombat code :-P

// this is WRONG
while (($key = array_search("a", $code)) != NULL)
{
// infinite loop, regardless of the unset
unset($code[$key]);
}

// this is _RIGHT_
while (($key = array_search("a", $code)) !== NULL)
{
// loop will terminate
unset($code[$key]);
}
?>
nan at designpromote dot co dot uk
1 year ago
$array = ['a', 'b', 'c'];
$key = array_search('a', $array); //$key = 0
if ($key)
{
//even a element is found in array, but if (0) means false
//...
}

//the correct way
if (false !== $key)
{
//....
}

It's what the document stated "may also return a non-Boolean value which evaluates to FALSE."
stooshie at gmail dot com
4 years ago
Example of a recursive binary search that returns the index rather than boolean.
<?php
// returns the index of needle in haystack
function binSearch($needle, $haystack)
{
   
// n is only needed if counting depth of search
   
global $n;
   
$n++;
   
// get the length of passed array
   
$l = count($haystack);
   
// if length is 0, problem
   
if($l <= 0)
    {
        return -
1;
    }
   
// get the mid element
   
$m = (($l+($l%2))/2);
   
// if mid >= length (e.g. l=1)
   
if($m >= $l)
    {
       
$m = $m-1;
    }
   
// get the indexed element to compare to the passed element and branch accordingly
   
$compare = $haystack[$m];
    switch(
true)
    {
        case(
$compare>$needle):
        {
           
// recurse on the lower half
           
$new_haystack = array_slice($haystack, 0, $m);
           
$c = count($new_haystack);
           
$r = binSearch($needle, $new_haystack);
           
// return current index - (length of lower half - found index in lower half)
           
return $m - ($c - $r);
            break;
        }
        case(
$compare<$needle):
        {
           
// recurse on the upper half
           
$new_haystack = array_slice($haystack, $m, ($l-$m));
           
$c = count($new_haystack);
           
$r = binSearch($needle, $new_haystack);
           
// return current position + found index in upper half
           
return $m + $r;
            break;
        }
        case(
$compare==$needle):
        {
           
// found it, so return index
           
return $m;
            break;
        }
    }
}
?>
n-regen
6 years ago
If you only know a part of a value in an array and want to know the complete value, you can use the following function:
<?php
function array_find($needle, $haystack)
{
   foreach (
$haystack as $item)
   {
      if (
strpos($item, $needle) !== FALSE)
      {
         return
$item;
         break;
      }
   }
}
?>
The function returns the complete first value of $haystack that contains $needle.
sunelbe at gmail dot com
3 years ago
hey i have a easy multidimensional array search function

<?php
function search($array, $key, $value)
{
   
$results = array();

    if (
is_array($array))
    {
        if (isset(
$array[$key]) && $array[$key] == $value)
           
$results[] = $array;

        foreach (
$array as $subarray)
           
$results = array_merge($results, search($subarray, $key, $value));
    }

    return
$results;
}
?>
dennis dot decoene at removthis dot moveit dot be
12 years ago
It has been said before: array_search is VERY slow. Everyone knows binary search is fast by design. Here is an implementation.

<?php
$arr
=array(1,3,5,7,9,10,11,13);
$searchfor = 6;
echo
binsearch($searchfor, $arr);

/**
* @return integer
* @param var $needle
* @param array $haystack
* @desc Feed a sorted array to $haystack and a value to search for to $needle.
             It will return false if not found or the index where it was found.
             This function is superfast. Try an array with 50.000 elements and search for something,
             you will be amazed.
*/
function binsearch($needle, $haystack)
{
   
$high = count($haystack);
   
$low = 0;
   
    while (
$high - $low > 1){
       
$probe = ($high + $low) / 2;
        if (
$haystack[$probe] < $needle){
           
$low = $probe;
        }else{
           
$high = $probe;
        }
    }

    if (
$high == count($haystack) || $haystack[$high] != $needle) {
        return
false;
    }else {
        return
$high;
    }
}
?>
marvin dot petker at borntocreate dot de
1 year ago
Be aware of using array_search() in conditional statements.

$foo = array("one", "two");
if( $key = array_search("one", $foo) ){
  echo "Found";
}
else{
  echo "Not found";
}
//Ouput: Not found

"Not found" will be outputted beacause the returned key is 0 and that will be interpreted as false in conditional statements.
tony dot peter at wanadoo dot fr
6 years ago
A simple recursive array_search function :

<?php
function recursive_array_search($needle,$haystack) {
    foreach(
$haystack as $key=>$value) {
       
$current_key=$key;
        if(
$needle===$value OR (is_array($value) && recursive_array_search($needle,$value))) {
            return
$current_key;
        }
    }
    return
false;
}
?>
sneskid at hotmail dot com
4 years ago
I had an array of arrays and needed to find the key of an element by comparing actual reference.
Beware that even with strict equality (===) php will equate arrays via their elements recursively, not by a simple internal pointer check as with class objects. The === can be slow for massive arrays and also crash if they contain circular references.

This function performs reference sniffing in order to return the key for an element that is exactly a reference of needle.

<?php
function array_ref_search(&$v, array &$s)
{
    if(
is_object($v)){ return array_search($v, $s, true); }
    foreach(
$s as $rK => &$rV)
    {
// reference sniff
       
$tV = $v;
        if( (
$rV === ($v = 1)) && ($rV === ($v = 0)) ){
       
$v = $tV; return $rK; }
       
$v = $tV;
    }
    return
false; // use null for php < 4.2.0
}

$list   = array();
$list['A'] = &$valA; $list['B'] = &$valB;

$valA = 1; $valB = 1;
echo
'array_ref_search: ', array_ref_search($valB, $list), '</br>'; // key 'B'
echo 'array_search:     ', array_search($valB, $list, true), '</br>'; // key 'A'

$valA = array(1,2,3); $valB = array(1,2,3);
echo
'array_ref_search: ', array_ref_search($valB, $list), '</br>'; // key 'B'
echo 'array_search:     ', array_search($valB, $list, true), '</br>'; // key 'A' because ($valA === $valB) is true by elements

$valB[] = &$valB; // circular reference
echo 'array_ref_search: ', array_ref_search($valB, $list), '</br>'; // key 'B'
echo 'array_search:     ', array_search($valB, $list, true), '</br>'; // crash because ($valB === $valB) causes infinite loop
?>
11 years ago
There is no function to count the occurences of needle in haystack, so I made my own one...

<?php
function array_match($needle, $haystack)
{
    if( !
is_array($haystack) ) return false;
   
   
$i = 0;
    while( (
in_array( $needle, $haystack )) != FALSE )
    {
       
$i++;
       
$haystack[array_search($needle, $haystack)] = md5($needle);
       
reset($haystack);
    }
   
    return
$i;
}
?>

I know it's a bit crappy, but don't ask me too much, I'm still only 13... ;)
mark dot php at mhudson dot net
9 years ago
I was going to complain bitterly about array_search() using zero-based indexes, but then I realized I should be using in_array() instead.

// if ( isset( $_GET['table'] ) and array_search( $_GET['table'], $valid_tables) ) {  // BAD: fails on first[0] element
// if ( isset( $_GET['table'] ) and ( FALSE !== array_search( $_GET['table'], $valid_tables) ) ) { OK: but wasteful and convoluted
   if ( isset( $_GET['table'] ) and in_array( $_GET['table'], $valid_tables) ) { // BETTER

The essence is this: if you really want to know the location of an element in an array, then use array_search, else if you only want to know whether that element exists, then use in_array()
swbrown at ucsd dot edu
14 years ago
Be absolutely sure to check that your code that uses array_search now checks for 'false' too if you upgrade to PHP 4.2.0!

I was using array_search in my page authentication routines and this change had the fun side-effect of causing my code to always think a user had full permissions!  It was letting anyone click through to our installation of phpMyAdmin.  Not good indeed!
robert at robert-gonzalez dot com
5 years ago
I needed a way to find the parent hierarchy of a multidimensional array. Being the rogue that I am, I got to coding before searching the manual and came up with two little functions that will return a parent stack for a first find and a complete parent stack, similar in nature to the solution presented by jette at nerdgirl dot dk without all the extra stuff or use of eval(). ;)

<?php
/**
* Gets the parent stack of a string array element if it is found within the
* parent array
*
* This will not search objects within an array, though I suspect you could
* tweak it easily enough to do that
*
* @param string $child The string array element to search for
* @param array $stack The stack to search within for the child
* @return array An array containing the parent stack for the child if found,
*               false otherwise
*/
function getParentStack($child, $stack) {
    foreach (
$stack as $k => $v) {
        if (
is_array($v)) {
           
// If the current element of the array is an array, recurse it and capture the return
           
$return = getParentStack($child, $v);
           
           
// If the return is an array, stack it and return it
           
if (is_array($return)) {
                return array(
$k => $return);
            }
        } else {
           
// Since we are not on an array, compare directly
           
if ($v == $child) {
               
// And if we match, stack it and return it
               
return array($k => $child);
            }
        }
    }
   
   
// Return false since there was nothing found
   
return false;
}

/**
* Gets the complete parent stack of a string array element if it is found
* within the parent array
*
* This will not search objects within an array, though I suspect you could
* tweak it easily enough to do that
*
* @param string $child The string array element to search for
* @param array $stack The stack to search within for the child
* @return array An array containing the parent stack for the child if found,
*               false otherwise
*/
function getParentStackComplete($child, $stack) {
   
$return = array();
    foreach (
$stack as $k => $v) {
        if (
is_array($v)) {
           
// If the current element of the array is an array, recurse it
            // and capture the return stack
           
$stack = getParentStackComplete($child, $v);
           
           
// If the return stack is an array, add it to the return
           
if (is_array($stack) && !empty($stack)) {
               
$return[$k] = $stack;
            }
        } else {
           
// Since we are not on an array, compare directly
           
if ($v == $child) {
               
// And if we match, stack it and return it
               
$return[$k] = $child;
            }
        }
    }
   
   
// Return the stack
   
return empty($return) ? false: $return;
}

// TESTING
$array = array(
   
'balloon' => array(
       
'red' => array(1 => 'Love', 'Valentine', 'Heart',),
       
'green' => array(1 => 'Summertime', 'Hope',),
    ),
   
'ribbon' => array(
       
'yellow' => array(2 => 'Welcome',),
       
'red' => array(3 => 'Love', 'Love',),
    ),
);

$s = getParentStack('Love', $array);
$c = getParentStackComplete('Love', $array);
var_dump($s, $c);
?>

Output:

array
  'balloon' =>
    array
      'red' =>
        array
          1 => string 'Love' (length=4)

array
  'balloon' =>
    array
      'red' =>
        array
          1 => string 'Love' (length=4)
  'ribbon' =>
    array
      'red' =>
        array
          3 => string 'Love' (length=4)
          4 => string 'Love' (length=4)
temporal dot pl at gmail dot com
6 years ago
Sometimes you need to find a given value in a sorted array or - if not found - detect the place where it should be. After that you can for example split the array into two halves, the  greater and the smaller one.

greenmr, dennis.decoene and php at celerondude had all posted very good binary search functions but these functions all return false if the needle was not found in the haystack. I've tweaked greenmr's code a little:

<?php
function Array_BinarySearch( $needle, $haystack, $comparator , &$probe )
{
   
$high = Count( $haystack ) -1;
   
$low = 0;
   
    while (
$high >= $low )
    {
       
$probe = Floor( ( $high + $low ) / 2 );
       
$comparison = $comparator( $haystack[$probe], $needle );
        if (
$comparison < 0 )
        {
           
$low = $probe +1;
        }
        elseif (
$comparison > 0 )
        {
           
$high = $probe -1;
        }
        else
        {
            return
true;
        }
    }
   
//The loop ended without a match
    //Compensate for needle greater than highest haystack element
   
if($comparator($haystack[count($haystack)-1], $needle) < 0)
    {
       
$probe = count($haystack);
    }
    return
false;
}
?>

Now, the function returns true if it finds something and false otherwise. If a needle was found, then $probe will contain it's position. Otherwise, $probe will contain position of where the needle would be if it were there :). This is possible because we pass $probe by reference.

Example:

<?php
//ultra-simple comparator :)
function CompareNumbers($obj, $needle)
{
    return
$obj - $needle;
}

//use examples
$testArr = array(10, 20, 30, 40, 50);
$res = Array_BinarySearch(30, $testArr, 'CompareNumbers', $probe);
echo (int)
$res.' '.$probe.'<br />';
//output is: 1 2 - found at position 2

$res = Array_BinarySearch(45, $testArr, 'CompareNumbers', $probe);
echo (int)
$res.' '.$probe.'<br />';
//output is: 0 4 - not found, but it would be at position 4 (between 40 and 45)

$res = Array_BinarySearch(-3, $testArr, 'CompareNumbers', $probe);
echo (int)
$res.' '.$probe.'<br />';
//output is: 0 0 - not found, but it would be at position 0 (before 10)

$res = Array_BinarySearch(300, $testArr, 'CompareNumbers', $probe);
echo (int)
$res.' '.$probe.'<br />';
//output is: 0 5 - not found, but it would be at position 5 (after 50; note, that count($haystack) == 5)
?>

See original greenmr's note for additional details about usage of this binary search: http://php.net/manual/en/function.array-search.php#89413
superbueno at gmail dot com
1 year ago
Like many others, === failed for a 0-indexed occurrence.  My solution was to test if an integer returned:

if ( is_int ( array_search($value, $array) ) ) return true;
raat1979 at gmail dot com
9 months ago
I needed to search for sequences of values in an array,
In addition I needed to search from a given offset.
Unfortunately for neither I could find a function to do this.

This Is how I did it,
The function returns the position where position 0 of the needle matches
<?php
function array_find($needle,array $haystack,$offset=0,$length=null,$strict = false,$returnAll = false,$resultsBeforeStart=false){
    if(
count($haystack)===0) return false; //empty haystack never contain a needle
   
if($offset>count($haystack)) return false; //looking higher then the top of the haystack will never find anything
   
if($offset!==0)    $haystack = array_slice($haystack, $offset, $length , true);
    if(
is_array($needle) && count($needle)===1) $needle = array_pop($needle);
    if(!
is_array($needle)){
       
$matches = array_keys($haystack,$needle,$strict);
    }else{
       
$needleKeys = array_keys($needle); //becomes array(0=>1,1=>4);
       
$needlePositions = array();
        foreach(
$needleKeys as $key=>$pos){                                   
           
$needlePartPositions = array_keys($haystack,$needle[$pos],$strict);   
            if(
count($needlePartPositions)===0) return false;                   
            foreach(
$needlePartPositions as $fkey=>$fval){                       
               
//we correct the found fosition based on the position in the needle, as a result
                //all matches set at the match position relative to start of needle
               
$matchStart = $fval-$pos;                                        
                if(
$matchStart >= 0 && ($matchStart>=$offset || $resultsBeforeStart)){                                           
                    if(!isset(
$needlePositions[$matchStart])){                   
                       
$needlePositions[$matchStart] = 1;                       
                    }else{
                       
$needlePositions[$matchStart]++;                           
                    }
                }
               
            }
        }
       
$matches = array_keys($needlePositions,count($needle),true);            //find all matches for which the position count matches the needle count
   
}
    if(
$matches === false) return false;
    if(
count($matches)===0) return false;
    if(
$returnAll) return $matches;
    return
array_shift($matches);

}

$needle1 = array(1=>'D',4=>'G');
$needle2 = array('D','E');
$needle3 = array(1=>'D',2=>'E');

               
// 0   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25
$haystack = array('A','B','C','D','E','F','G','H','I','J','H','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
               
//26  27  28  29  30  31  32  33  34  35  36  37  38  39  40  41  42  43  44  55  46  47  48  49  50  51
                 
'A','B','C','D','E','F','G','H','I','J','H','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
               
//52  53  54  55  56      57  58  59  60  61  62  63  64  65  66  67  68  69  70  71  72  73  74  75  76
                 
'A','B','C','D','E',    'G','H','I','J','H','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');

var_dump(array_find($needle1,$haystack,0,null,true,true));
var_dump(array_find($needle1,$haystack,29,null,true,true));
var_dump(array_find($needle1,$haystack,29,null,true,true,true));

var_dump(array_find($needle2,$haystack,0,null,true,true));
var_dump(array_find($needle2,$haystack,55,null,true,false));
var_dump(array_find($needle2,$haystack,56,null,true,false,true));

?>       
// D is at position 3 and 29 but they are matched at position 1 of the needle
// position 0 of the needle would therefore be at 2 and 28
array(2) {
  [0]=>  int(2)
  [1]=>  int(28)
}

//no match after position 29 that is after the start position
bool(false)

// items in the needle are matched at position 29 but needle starts at 1, $resultsBeforeStart was true so this one is included
array(1) {
  [0]=>  int(28)
}

// D,E found at 3 positions
array(3) {
  [0]=>  int(3)
  [1]=>  int(29)
  [2]=>  int(55)
}

//search for D,E starting at position 55 finds 1 match
int(55)

//search for D,E starting at position 56 finds NO matches, even if $resultsBeforeStart is set to true because the needle starts at position 0
bool(false)
rAthur
2 years ago
If you're not running an older version of PHP (many servers are still on PHP 5.3), you can replace the function by this :

<?php

function s($needle,$array)
{
    foreach(
$array as $key => $value)
        if (
$value==$needle)
        return
$key;
    return
false;
}

echo
s( 'c', array('a', 'b', 'c', 'd') ); // returns 2
echo s( 'f', array('a', 'b', 'c', 'd') ); // returns false

?>
rAthur
2 years ago
If you're not running an older version of PHP (many servers are still on PHP 5.3), you can replace the function by this :

<?php

function s($needle,$array)
{
    foreach(
$array as $key => $value)
        if (
$value==$needle)
        return
$key;
    return
false;
}

echo
s( 'c', array('a', 'b', 'c', 'd') ); // returns 2
echo s( 'f', array('a', 'b', 'c', 'd') ); // returns false

?>
podarokua at gmail dot com
1 year ago
Here is a method for getting all keys, containing searched value, recursively

  /**
   * Recursive array search.
   *
   * See http://php.net/manual/en/function.array-search.php#91365
   *
   * @param $needle
   *   The searched value.
   * @param $haystack
   *   The array.
   *
   * @return bool|int|string
   *   Array of keys, containing values or FALSE if not found.
   */
  private function ras($needle, $haystack) {
    $keys = array();
    foreach ($haystack as $key => $value) {
      if ($needle === $value OR (is_array($value) && $this->ras(
            $needle,
            $value
          ) !== FALSE)
      ) {
        $keys[] = $key;
      }
    }
    if (!empty($keys)) {
      return $keys;
    }

    return FALSE;
  }
dk at danilok dot com
1 year ago
I needed a way to return the value of a single specific key, thus:

<?php

function recursive_return_array_value_by_key($needle, $haystack){
   
$return = false;
    foreach(
$haystack as $key => $val){
        if(
is_array($val)){
           
$return = recursive_return_array_value_by_key($needle, $val);
        }
        else if(
$needle === $key){
            return
"$val\n";
        }
    }
    return
$return;
}

?>
Dave C
4 years ago
Here is a version of binary search that is done via recursion instead of iteration.  Remember that your data needs to be presorted!

<?php
static function Bin_Search(&$needle, &$haystack, $start, $end) {
        if(
$end < $start)
        {
            return
false;
        }

       
$mid = (int)(($end - $start) / 2) + $start;
 
        if(
$haystack[$mid] > $needle)
        {
            return
Bin_Search($needle, $haystack, $start, $mid - 1);
        }
        else if(
$haystack[$mid] < $needle)
        {
            return
Bin_Search($needle, $haystack, $mid + 1, $end);
        }
        else
        {
            return
true;
        }
}
?>
codeslinger at compsalot dot com
6 years ago
one thing to be very aware of is that array_search() will fail if the needle is a string and the array itself contains values that are mixture of numbers and strings.  (or even a string that looks like a number)

The problem is that unless you specify "strict" the match is done using ==    and in that case any string will match a numeric value of zero which is not what you want.

-----

also, php can lookup an index pretty darn fast.  for many scenarios, it is practical to maintain multiple arrays, one in which the index of the array is the search key and the normal array that contains the data.

<?php

  $normal
[$index] = array('key'=>$key, 'data'=>'foo');
 
$inverse[$key] = $index;

 
//very fast lookup, this beats any other kind of search

 
if (array_key_exists($key, $inverse))
  {
   
$index = $inverse[$key];
    return
$normal[$index];
  }

?>
Nguyen KimKha
6 years ago
You can remove some values from array, by using unset() and array_search().

<?php

$friends
= array( 'Bob', 'Ann', 'Peter' ); // Two persons named 'Bob'
$find = 'Bob';
$key = array_search( $find, $friends ); // Find key of given value
if ($key != NULL || $key !== FALSE) {
    unset(
$friends[$key]); // remove key from array
}

// Now, $friends = array( 'Ann', 'Peter');

?>
helenadeus at gmail dot com
7 years ago
I was trying to use array_search to retrieve all the values that match a given needle, but it turns out only the first match key is returned. I built this little function, which works just like array_search, but returns all the keys that match a given needle instead. The output is an array.

<?php

$haystack
= array('a','b','a','b');

$needle = 'a';

print_r(array_search_all($needle, $haystack));

//Output will be
// Array
// (
//         [0]=>1
//         [1]=>3
// )

function array_search_all($needle, $haystack)
{
#array_search_match($needle, $haystack) returns all the keys of the values that match $needle in $haystack

   
foreach ($haystack as $k=>$v) {
   
        if(
$haystack[$k]==$needle){
       
          
$array[] = $k;
        }
    }
    return (
$array);

   
}

?>
dcez at land dot ru
8 years ago
Simple way to get variable name by using array_search function:

<?php

function varname($var){

    return (isset(
$var))? array_search($var, $GLOBALS) : false;

}

$boogie = 'tonight';

echo
varname($boogie);

?>
azaozz, gmail
7 years ago
Expanding on the comment by hansen{}cointel.de:

When searching for a string and the array contains 0 (zero), the string is casted to (int) by the type-casting which is always 0 (perhaps the opposite is the proper behaviour, the array value 0 should have been casted to string). That produces unexpected results if strict comparison is not used:

<?php
$a
= array(0, "str1", "str2", "str3");
echo
"
str1 = "
.array_search("str1", $a).",
str2 = "
.array_search("str2", $a).",
str3 = "
.array_search("str3", $a).",

str1 strict = "
.array_search("str1", $a, true).",
str2 strict = "
.array_search("str2", $a, true).",
str3 strict = "
.array_search("str3", $a, true);
?>

This will return:
str1 = 0, str2 = 0, str3 = 0, str1 strict = 1, str2 strict = 2, str3 strict = 3
andreas dot damm at maxmachine dot de
8 years ago
Combining syntax of array_search() and functionality of array_keys() to get all key=>value associations of an array with the given search-value:
<?php
function array_search_values( $m_needle, $a_haystack, $b_strict = false){
    return
array_intersect_key( $a_haystack, array_flip( array_keys( $a_haystack, $m_needle, $b_strict)));
}
?>

Usage:
<?php
$array1
= array( 'pre'=>'2', 1, 2, 3, '1', '2', '3', 'post'=>2);
print_r( array_search_values( '2', $array1));
print_r( array_search_values( '2', $array1, true));
print_r( array_search_values( 2, $array1, true));
?>

Will return:
array(4) {
    ["pre"] =>
    string(1) "2"
    [1] =>
    int(2)
    [4] =>
    string(1) "2"
    ["post"] =>
    int(2)
}
array(2) {
    ["pre"] =>
    string(1) "2"
    [4] =>
    string(1) "2"
}
array(2) {
    [1] =>
    int(2)
    ["post"] =>
    int(2)
}
robertark at gmail dot com
8 years ago
A better array_isearch would be to store all results in an array, then return the KEYS stored in $found, such as:

<?php
function array_isearch($str, $array){
 
$found = array();
  foreach (
$array as $k => $v)
      if (
strtolower($v) == strtolower($str)) $found[] = $k;
  return
$found;
}
?>

To use, simply have an array to search from then search it, for example:

<?php

function array_isearch($str, $array) {
 
$found = array();
  foreach(
$array as $k => $v)
    if(
strtolower($v) == strtolower($str)) $found[] = $k;
  return
$found;
}

$stored = "these are an array";
$stored = explode(" ", $stored);

$compare = array("these", "are", "some", "results", "stored", "in", "an", "array");
foreach(
$stored as $store) {
 
$results = array_isearch($store, $compare);
  foreach(
$results as $key => $result)
    echo
"Key: ".$results[$key]."<br />Found: ".$compare[$result]."<br />";
}

?>

Hope this helps :-)

-Rob
congaz at yahoo dot dk
10 years ago
Search a multi-dimensional array on keys!
-------------------------------------------

I needed to search dynamically in a multi-dimen array on keys. I came up with this little neat function. It is so amazingly simple, that I actually didn't think it would work - but it does...

mixed array_searchMultiOnKeys(array, array);

<?php
function array_searchMultiOnKeys($multiArray, $searchKeysArray) {
   
// Iterate through searchKeys, making $multiArray smaller and smaller.
   
foreach ($searchKeysArray as $keySearch) {
       
$multiArray = $multiArray[$keySearch];
       
$result = $multiArray;
    }
   
   
// Check $result.
   
if (is_array($multiArray)) {
       
// An array was found at the end of the search. Return true.
       
$result = true;
    }
    else if (
$result == '') {
       
// There was nothing found at the end of the search. Return false.
       
$result = false;
    }

    return
$result;
// End of function,
}

// --- Test array_searchMultiOnKeys ---
$multiArray['webpages']['downloads']['music'] = 1;
$multiArray['webpages']['downloads']['pressmaterial'] = 5;
$multiArray['webpages']['links'] = 7;

array_searchMultiOnKeys($multiArray, array('webpages', 'links')); // returns 7.
array_searchMultiOnKeys($multiArray, array('webpages', 'downloads')); // returns true.
array_searchMultiOnKeys($multiArray, array('webpages', 'downloads', 'software')); // returns false.

?>

$multiArray / $searchKeysArray can be any size.

Happy hacking...
10 years ago
may be good to take note of PHP's mind-boggling 'fuzzy' (vulgo "magic type-casting") comparison features not only in using the results, but also in the search, too:
<?php
$a
=array("a","b",0,"c","d");
echo
"a: ".array_search("a",$a);
echo
"b: ".array_search("b",$a);
echo
"c: ".array_search("c",$a);
echo
"d: ".array_search("d",$a);
echo
"0: ".array_search("0",$a);
echo
"x: ".array_search("x",$a);
echo
"1: ".array_search("1",$a);
?>
will result in:
a: 0, b: 1, c: 2, d: 2, 0: 2, x: 2, 1: false

as from "c" on, the first match found in $a is "0", as any string compared to an int is automatically cast to (int)0.
dmitry dot polushkin at gmail dot com
9 years ago
To get the key of the found search value, use:
<?php
$a
= array('a', 'b', 'c');
echo
array_search(array_search('c', $a), array_keys($a));
?>
php at celerondude dot com
12 years ago
I think array_search uses serial search because they binary search function i wrote here seems to do a better job for records that are not always at the beginning of the array.

Here it is

<?php
function binarySearch ( $a, $t, $l, $r )
{
    if(
$t<$a[$l]||$t>$a[$r])return NULL;
    while (
$l < $r )
    {
       
$m=intval($l+$r)/2;
        if(
$a[$m]==$t)return $m;
        elseif(
$t<$a[$m])$r=$m-1;
        elseif(
$t>$a[$m])$l = $m + 1;
    }
    if(
$t==$a[$r])
    return
$r;
    return
NULL;
}
?>

usage:
binarySearch ( array, target, left range, right range );

if your array is a multidimensional array, simply change the comparison method. :)
kermes [at] thesevens [dot] net
8 years ago
A variation of previous searches that returns an array of keys that match the given value:

<?php
function array_ksearch($array, $str)
{
   
$result = array();
    for(
$i = 0; $i < count($array); next($array), $i++)
        if(
strtolower(current($array)) == strtolower($str))
           
array_push($result, key($array);
   
    return
$result;
}
?>

Usage would be as follows:
<?php
$testArray
= array('one' => 'test1', 'two' => 'test2', 'three' => 'test1', 'four' => 'test2', 'five' => 'test1');
   
print_r(array_ksearch($testArray, 'test1'));
?>
rAthur
2 years ago
If you're not running an older version of PHP (many servers are still on PHP 5.3), you can replace the function by this :

<?php

function s($needle,$array)
{
    foreach(
$array as $key => $value)
        if (
$value==$needle)
        return
$key;
    return
false;
}

echo
s( 'c', array('a', 'b', 'c', 'd') ); // returns 2
echo s( 'f', array('a', 'b', 'c', 'd') ); // returns false

?>
RichGC
10 years ago
To expand on previous comments, here are some examples of
where using array_search within an IF statement can go
wrong when you want to use the array key thats returned.

Take the following two arrays you wish to search:

<?php
$fruit_array
= array("apple", "pear", "orange");
$fruit_array = array("a" => "apple", "b" => "pear", "c" => "orange");

if (
$i = array_search("apple", $fruit_array))
//PROBLEM: the first array returns a key of 0 and IF treats it as FALSE

if (is_numeric($i = array_search("apple", $fruit_array)))
//PROBLEM: works on numeric keys of the first array but fails on the second

if ($i = is_numeric(array_search("apple", $fruit_array)))
//PROBLEM: using the above in the wrong order causes $i to always equal 1

if ($i = array_search("apple", $fruit_array) !== FALSE)
//PROBLEM: explicit with no extra brackets causes $i to always equal 1

if (($i = array_search("apple", $fruit_array)) !== FALSE)
//YES: works on both arrays returning their keys
?>
hanan dot ali dot shaikh at googlemail dot com
5 years ago
In this code I write a code to find next and previous element of an array using current element of that array. Let suppose if we are in element 9 and have to access its next and previous element then this code be helpful for someone.

<?php
$myArray
= array(4,5,7,9,10,11,13,19,25);

$currentElement = 9;
$firstElement = current($myArray);
$lastElement = $myArray[sizeof($myArray)-1];

$currentKey = array_search($currentElement, $myArray);
$currentValue = $myArray[$currentKey];

$previousValue = "";
$nextValue = "";
if(
$currentElement!=$lastElement){
   
$nextKey = $currentKey + 1;
   
$nextValue = $myArray[$nextKey];
}

if(
$currentElement!=$firstElement){
   
$previousKey = $currentKey - 1;
   
$previousValue = $myArray[$previousKey];
}

echo
$previousValue."--".$currentValue."--".$nextValue;

?>

Thanks,
Hanan Ali
emanuel dot tavares at connix dot com dot br
1 year ago
Hi!

I've tried to use array_search to fill an array with registers from a database seach with this:

$registros = 0;

while ( $row = $this->result->fetch_array() )
{
      if ( !array_search($row[cd_subsecao], $this->listaSecoes) )
                  $registros = array_push($this->listaSecoes, $row[cd_subsecao]);
}

But the result was:

Array
(
    [0] => obr
    [1] => obr
    [2] => obr
    [3] => a10
    [4] => obr
    [5] => obr
    [6] => obr
)

It was caused by because the first element has repetitions.

Then I've tried to substitute the !array_search.... for array_search(...) == FALSE, but it didn't worked too.

The solution was to use the "===":

$registros = 0;

while ( $row = $this->result->fetch_array() )
{
      if ( array_search($row[cd_subsecao], $this->listaSecoes) === FALSE)
                  $registros = array_push($this->listaSecoes, $row[cd_subsecao]);
}

It returned:

Array
(
    [0] => obr
    [1] => a10
)
php5 site builder
8 years ago
If you encounter a situation where condition test is failing on the result of either array_search or in_array, even when using "===" and "!==", make sure to set $strict = true in your array_search() or in_array() function call.

A situation such as :

$arTemp[0] = 1;
$arTemp[1] = 0;
$arTemp[2] = 3;
$arTemp[3] = 5;
$sTempTest = 'BLAH';

$bResult = in_array($sTempTest,$arTemp);
$bResult2 = array_search($sTempTest,$arTemp);

var_dump($bResult);
var_dump($bResult2);

will result in :

boolean true
int 1

Using :

$bResult = in_array($sTempTest,$arTemp,true);
$bResult2 = array_search($sTempTest,$arTemp,true);

will yield :
boolean false
boolean false

This is necessary in any instance where you have an array value equal to the integer zero.  As soon as you put the zero in quotes or double quotes (a string), the evaluation works with in_array & array_search without the $strict parameter being set.
elvenone at gmail dot com
9 years ago
<?php
               
// Search an array in reverse order.
       
function array_reverse_search($value, $array) {
             for(
$i = sizeof($array)-1; $i>=0; $i--) {
                if (
$array[$i] == $value) return $i;
             }
            return -
1;    
        }
?>
richard at richard-sumilang dot com
13 years ago
<?php
/**
     *    Search an array recursivly
     *
     *    This function will search an array recursivly
     *    till it finds what it is looking for. An array
     *    within an array within an array within array
     *    is all good :-)
     *
     *    @author        Richard Sumilang    <richard@richard-sumilang.com>
     *    @param        string    $needle        What are you searching for?
     *    @param        array    $haystack    What you want to search in
     *    @return        boolean
     *    @access        public
     */
   
function array_search_r($needle, $haystack){
        foreach(
$haystack as $value){
            if(
is_array($value))
               
$match=array_search_r($needle, $value);
            if(
$value==$needle)
               
$match=1;
            if(
$match)
                return
1;
        }
        return
0;
    }
?>
To Top