Web студия "GrandView"
  Главная   Написать Контакты
   
   
О проекте
Руководство php
 

array_search

(PHP 4 >= 4.0.5, PHP 5)

array_search --  Осуществляет поиск данного значения в массиве и возвращает соответствующий ключ в случае удачи

Описание

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

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

Замечание: Если needle является строкой, производится регистро-зависимое сравнение.

Замечание: До PHP 4.2.0, array_search() при неудаче возвращала NULL вместо FALSE.

Если вы передадите значение TRUE в качестве необязательного третьего параметра strict, функция array_search() также проверит тип needle в массиве haystack.

Если needle присутствует в haystack более одного раза, будет возвращён первый найденный ключ. Для того, чтобы возвратить ключи для всех найденных значений, используйте функцию array_keys() с необязательным параметром search_value.

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

<?php
$array
= array(0 => 'blue', 1 => 'red', 2 => 0x000000, 3 => 'green', 4 => 'red');

$key = array_search('red', $array);         // $key = 1;
$key = array_search('green', $array);       // $key = 2; (0x000000 == 0 == 'green')
$key = array_search('green', $array, true); // $key = 3;
?>

Внимание

Эта функция может возвращать как логическое значение FALSE, так и не относящееся к логическому типу значение, которое приводится к FALSE, например, 0 или "". За более подробной информации обратитесь к разделу Булев тип. Используйте оператор === для проверки значения, возвращаемого этой функцией.

См. также array_keys(), array_values(), array_key_exists(), и in_array().



array_shift> <array_reverse
Last updated: Sat, 27 Jan 2007
 
add a note add a note User Contributed Notes
array_search
zwijntje82 at hotmail dot com
21-Sep-2007 12:39
use 3x === if you want to kill doubles in an array.
others will not work

if(array_search($twee[0],$y)===false){
echo $twee[0].array_search($twee[0],$y).'<br>';
}
kermes [at] thesevens [dot] net
11-Sep-2007 03:09
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'));
?>
robertark at gmail dot com
01-Sep-2007 11:20
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
xurizaemon
12-Jul-2007 06:11
@ ben, your array_isearch function returns the value, while array_search returns the key. to get equivalent (but case-insensitive) functionality, you would return $k not $v.
ben at reload dot me dot uk
25-May-2007 11:50
A refinement on chappy at citromail dot hu's case-insensitive search function...

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

Shall return false on no match or return the first value that matches if one or more matches are found (same functionality as the array_search() function).  It is also more efficient as it stops searching the array once a match is found.
php5 site builder
23-May-2007 10:14
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.
rob at robspages dot net
16-Feb-2007 09:49
php dot net at surfnation dot de's function with a slight mod to correct for axo at axolander dot de's comments:

<?php

  
function multiArraySearch($needle, $haystack){
       
$value = false;
       
$x = 0;
        foreach(
$haystack as $temp){
                
$search = array_search($needle, $temp);
                 if (
strlen($search) > 0 && $search >= 0){
                     
$value[0] = $x;
                   
$value[1] = $search;
                      }
                
$x++;
            }
    return
$value;
  }
?>
axo at axolander dot de
14-Feb-2007 05:32
to php dot net at surfnation dot de

please make sure you read the warning on array_search - your multi-dimensional function will not return anything if the first element is the one you're looking for.
php dot net at surfnation dot de
03-Feb-2007 03:03
Here is my solution for a 2-dimensional search.
It combines the foreach with the faster array_search (I did use a recursive way, cause I am at war with it :) ).
it is quick, easy and (hopefully) very stable.

<?php

$map
= array();
$map[1][1] = 11;
$map[2][1] = 21;
$map[3][1] = 31;
$map[1][3] = 13;
$varGesuchtesElement = 21;

$varGefundenesElement = fktMultiArraySearch($map,$varGesuchtesElement);

if (
$varGefundenesElement){
   
print_r($varGefundenesElement);
}
else{
    echo
"Kein Element gefunden!";
}

function
fktMultiArraySearch($arrInArray,$varSearchValue){
   
    foreach (
$arrInArray as $key => $row){
       
$ergebnis = array_search($varSearchValue, $row);
       
        if (
$ergebnis){
           
$arrReturnValue[0] = $key;
           
$arrReturnValue[1] = $ergebnis;
            return
$arrReturnValue;
        }
    }
}

?>
elvenone at gmail dot com
27-Jan-2007 05:10
<?php
       
function array_reverse_search($value, $array) {
             for(
$i = sizeof($array)-1; $i>=0; $i--) {
                if (
$array[$i] == $value) return $i;
             }
            return -
1;    
        }
?>
francois at tekwire dot net
18-Jan-2007 02:34
Please note that, in PHP5, if you search for an object in an array using the array_search() function, PHP will return the first object whose properties match, not the same class and instance as your needle. In other words, the object comparison is of type '==', not '===' (see the 'Comparing objects' page).
erick dot xavier at gmail dot com
04-Jan-2007 04:57
Modifing the "multiarray_search" to unordered Array....
<?PHP
function multiarray_search($arrayVet, $campo, $valor){
    while(isset(
$arrayVet[key($arrayVet)])){
        if(
$arrayVet[key($arrayVet)][$campo] == $valor){
            return
key($arrayVet);
        }
       
next($arrayVet);
    }
    return -
1;
}

//I.e.:

$myArr = array(
   
13 => array(
       
"fruit" => "banana"
   
),
   
654 => array(
       
"fruit" => "apple"
   
),
   
2445 => array(
       
"fruit" => "nothing more"
   
)
);

print(
multiarray_search($myArr , "fruit", "apple"));

/*
Output:
654
*/

//and

print(multiarray_search($myArr , "fruit", "orange"));

/*
Output:
-1
*/
?>
otto at twbc dot net
13-Dec-2006 11:06
Unlimited depth array regular expression search, I found it useful, perhaps someone else will too. Searches on the array values only. Key search could be easily added.

function Array_Search_Preg( $find, $in_array, $keys_found=Array() )
{
    if( is_array( $in_array ) )
    {
        foreach( $in_array as $key=> $val )
        {
            if( is_array( $val ) ) $this->Array_Search_Preg( $find, $val, $keys_found );
            else
            {
                if( preg_match( '/'. $find .'/', $val ) ) $keys_found[] = $key;
            }
        }
        return $keys_found;
    }
    return false;
}
joltmans at bolosystems dot com
06-Dec-2006 03:25
You can use array_search to simply parse a CLI program's input parameters such as:

[user@server ~]$ ./someCLIprog.php --username user1 --password 123password --option1 whatever

You can easily parse this information using the following code snippets:
<?php

  
// Get the username
  
$userkey = array_search("--username", $argv);
  
// Make sure both that the token was found and followed by another valid token, AKA not one that begins with a -
  
if ($userkey && !empty($argv[$userkey+1]) && strcmp($argv[$userkey+1]{0}, '-')) {
      
$username = $argv[$userkey+1];
   }
  
// If you want the token to be required add the following else statement
  
else {
       exit(
"No username provided\n");
   }
  
// repeat for each optional parameter,
?>
evert_18 at hotmail dot com
13-Nov-2006 06:18
This function can search in multidimensional arrays, no mather how multidimensional the array is!

<?php
function array_search(&$array,$needle)
{
    foreach(
$array as $key => $value)
    {
        if(
$value == $needle || $key == $needle)
            return(
true);
        else
            if(
is_array($value))
               
$this->search($value,$needle);
            else
                return(
false);
    }
}
?>
dmitry dot polushkin at gmail dot com
21-Oct-2006 10:03
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));
?>
jupiter at nospam dot com
29-Sep-2006 02:25
Checks that array value STARTS with the string(needle), while other functions require an exact match OR the needle can be anywhere within.  This function can be manipulated to END with the needle if needed
<?php
// returns first key of haystackarray which array valuestring starts with needlestring, is case-sensitive
function arrayHaystackStartsWithNeedleString($haystackarray, $needlestring) {
    if (
is_array($haystackarray)) {  // confirms array
       
$needlelength = strlen($needlestring);  // length of string needle
       
foreach ($haystackarray as $arraykey => $arrayvalue) {  // gets array value
           
$arraypart = substr($arrayvalue, 0, $needlelength);  // first characters of array value
           
if ($needlestring == $arraypart) {  // did we find a match
               
return $arraykey// return will stop loop
           
// end match conditional
       
// end loop
   
// end array check
   
return false// no matches found if this far
}
?>
I haven't speed tested this, but it should be pretty quick.
Digitally Designed dot co dot uk
28-Sep-2006 02:48
My Function to search a Multidimensional array.

Pass in :

$theNeedle as what you want to find.
$theHaystack as the array
$keyToSearch as what key in the array you want to find the value in.

<?   

function myMulti_Array_Search($theNeedle, $theHaystack, $keyToSearch)
        {
        foreach($theHaystack as $theKey => $theValue)
            {
            $intCurrentKey = $theKey;   
               
            if($theValue[$keyToSearch] == $theNeedle)
                {
   
                return $intCurrentKey ;
                }
            else
                {
                return 0;
                }
            }
        }

?>
lars-magne
22-Sep-2006 05:19
Further comments on the multidimensional array searches given earlier:

I needed an extended search function which could search in both keys and values in any # dimension array and return all results. Each result contains key/value hit, type (key or value), key path and value (in case result is a key).

<?php

function array_search_ext($arr, $search, $exact = true, $trav_keys = null)
{
  if(!
is_array($arr) || !$search || ($trav_keys && !is_array($trav_keys))) return false;
 
$res_arr = array();
  foreach(
$arr as $key => $val)
  {
   
$used_keys = $trav_keys ? array_merge($trav_keys, array($key)) : array($key);
    if((
$key === $search) || (!$exact && (strpos(strtolower($key), strtolower($search)) !== false))) $res_arr[] = array('type' => "key", 'hit' => $key, 'keys' => $used_keys, 'val' => $val);
    if(
is_array($val) && ($children_res = array_search_ext($val, $search, $exact, $used_keys))) $res_arr = array_merge($res_arr, $children_res);
    else if((
$val === $search) || (!$exact && (strpos(strtolower($val), strtolower($search)) !== false))) $res_arr[] = array('type' => "val", 'hit' => $val, 'keys' => $used_keys, 'val' => $val);
  }
  return
$res_arr ? $res_arr : false;
}

// I.e.:
$haystack[754] = "Norwegian";
$haystack[28]['details']['Norway'] = "Oslo";
$needle = "Norw";

if(
$results = array_search_ext($haystack, $needle, false))
  foreach(
$results as $res)
    echo
"Found '$needle' in $res[type] '$res[hit]', using key(s) '".implode("', '", $res['keys'])."'. (Value: $res[val])<br />\n";

/* Printed result will be:
Found 'Norw' in val 'Norwegian', using key(s) '754'. (Value: Norwegian)
Found 'Norw' in key 'Norway', using key(s) '28', 'details', 'Norway'. (Value: Oslo)
*/

?>
mark dot php at mhudson dot net
11-Sep-2006 05:49
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()
ob at babcom dot biz
28-Aug-2006 02:55
This function is based on the function in comment "array_search" from July 26th 2006.

I added the possibility of defining the key which $Needle shall be searched for.

<?php
// search haystack for needle and return an array of the key path,
// FALSE otherwise.
// if NeedleKey is given, return only for this key
// mixed ArraySearchRecursive(mixed Needle,array Haystack
//                            [,NeedleKey[,bool Strict[,array Path]]])

function ArraySearchRecursive($Needle,$Haystack,$NeedleKey="",
                             
$Strict=false,$Path=array()) {
  if(!
is_array($Haystack))
    return
false;
  foreach(
$Haystack as $Key => $Val) {
    if(
is_array($Val)&&
      
$SubPath=ArraySearchRecursive($Needle,$Val,$NeedleKey,
                                    
$Strict,$Path)) {
     
$Path=array_merge($Path,Array($Key),$SubPath);
      return
$Path;
    }
    elseif((!
$Strict&&$Val==$Needle&&
           
$Key==(strlen($NeedleKey)>0?$NeedleKey:$Key))||
            (
$Strict&&$Val===$Needle&&
            
$Key==(strlen($NeedleKey)>0?$NeedleKey:$Key))) {
     
$Path[]=$Key;
      return
$Path;
    }
  }
  return
false;
}
?>

Remove unnecessary new lines. I had to add them because of too long lines.
26-Jul-2006 07:19
/**
 * Searches haystack for needle and returns an array of the key path if it is found in the (multidimensional) array, FALSE otherwise.
 *
 * mixed array_searchRecursive ( mixed needle, array haystack [, bool strict[, array path]] )
 */

function array_searchRecursive( $needle, $haystack, $strict=false, $path=array() )
{
    if( !is_array($haystack) ) {
        return false;
    }

    foreach( $haystack as $key => $val ) {
        if( is_array($val) && $subPath = array_searchRecursive($needle, $val, $strict, $path) ) {
            $path = array_merge($path, array($key), $subPath);
            return $path;
        } elseif( (!$strict && $val == $needle) || ($strict && $val === $needle) ) {
            $path[] = $key;
            return $path;
        }
    }
    return false;
}
gullevek at gullevek dot org
18-Apr-2006 10:31
There were two previous entries for having a recursive search. The first one only searched for values, second one for values with an optional key.

But both of those stopped after they found an entry. I needed, that it searches recursive, with optional key and returns me all matches found in the array.

So I wrote this function:

needle is the value you search, haystack is the array of course, key is the optional key in the array where the needle should be. path should be never set on intial call. its an internal used variable.

It returns an array $path with the array entry 'found' where you can find all found groups. In these groups you have the array which holds the keys to find the data.

I hope this helps some of you.

<?php
   
function array_search_recursive_all($needle, $haystack, $key, $path = NULL)
    {
        if (!
$path['level'])
           
$path['level'] = 0;
        if (!
$path['work'])
           
$path['work'] = array();
        if (!
is_array($haystack))
           
$haystack = array();

       
// go through the array,
       
foreach ($haystack as $_key => $_value)
        {
           
// only value matches
           
if (is_scalar($_value) && $_value == $needle && !$key)
            {
               
$path['work'][$path['level']] = $_key;
               
$path['found'][] = $path['work'];
            }
           
// key and value matches
           
elseif (is_scalar($_value) && $_value == $needle && $_key == $key)
            {
               
$path['work'][$path['level']] = $_key;
               
$path['found'][] = $path['work'];
            }
            elseif (
is_array($_value))
            {
               
// add position to working
               
$path['work'][$path['level']] = $_key;
               
// we will up a level
               
$path['level'] += 1;
               
// call recursive
               
$path = array_search_recursive_all($needle, $_value, $key, $path);
            }
        }
       
// cut all that is >= level
       
array_splice($path['work'], $path['level']);
       
// step back a level
       
$path['level'] -= 1;
        return
$path;
    }
?>

If you call it with this:

<?
    $right_side = array ('foo' => 'alpha', 'bar' => 'beta', 'delta' => 'gamma', 'gamma' => 'delta');
    $value = 'beta';
    $key = 'bar';
    $pos = array_search_recursive_all($value, $right_side, $key);
?>

You will find in $pos this data

<?
Array
(
    [level] => -1
    [work] => Array
        (
        )

    [found] => Array
        (
            [0] => Array
                (
                    [0] => bar
                )

        )

)
?>
RichGC
20-Mar-2006 05:54
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
?>
congaz at yahoo dot dk
09-Mar-2006 07:38
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...
chappy at citromail dot hu
11-Feb-2006 12:26
If you're searching for strings and you need a case-insensetive script, there's one:

function array_lsearch($str,$array){
    $found=array();
    foreach($array as $k=>$v){
        if(strtolower($v)==strtolower($str)){
            $found[]=$v;
        }
    }
    $f=count($found);
    if($f===0)return false;elseif($f===1)return $found[0];else return $found;
}

It returns the original string, not the lower. Also good if use strtoupper().
hansen{
Новости
11 июля 2007
Сайт запущен
© 2007 info@grandviewstudio.com

Deprecated: Function set_magic_quotes_runtime() is deprecated in /home/sites/grandviewstudiocom/www/65f67d67a94ad980786580ae69e11c07/sape.php on line 324

Deprecated: Function set_magic_quotes_runtime() is deprecated in /home/sites/grandviewstudiocom/www/65f67d67a94ad980786580ae69e11c07/sape.php on line 330
Z058440144362 Z348613067571