На странице произошла ошибка #S51. Свяжитесь с вебмастером. PHP 5.6 и PHP 7 на русском: Функция array_search() - Осуществляет поиск данного значения в массиве и возвращает соответствующий ключ в случае удачи

Коментарии

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]);
}
?>
2003-06-09 22:50:20
http://php5.kiev.ua/manual/ru/function.array-search.html
Автор:
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
?>
2006-03-20 07:54:15
http://php5.kiev.ua/manual/ru/function.array-search.html
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($resultkey($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'));
?>
2007-09-11 18:09:44
http://php5.kiev.ua/manual/ru/function.array-search.html
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_haystackarray_fliparray_keys$a_haystack$m_needle$b_strict)));
}
?>

Usage:
<?php
$array1 
= array( 'pre'=>'2'123'1''2''3''post'=>2);
print_rarray_search_values'2'$array1));
print_rarray_search_values'2'$array1true));
print_rarray_search_values2$array1true));
?>

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)
}
2008-04-03 19:07:52
http://php5.kiev.ua/manual/ru/function.array-search.html
Автор:
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"$atrue).",
str2 strict = "
.array_search("str2"$atrue).",
str3 strict = "
.array_search("str3"$atrue);
?>

This will return:
str1 = 0, str2 = 0, str3 = 0, str1 strict = 1, str2 strict = 2, str3 strict = 3
2008-12-20 19:23:43
http://php5.kiev.ua/manual/ru/function.array-search.html
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);

   
}

?>
2009-01-25 15:05:32
http://php5.kiev.ua/manual/ru/function.array-search.html
Автор:
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.
2009-05-05 13:36:48
http://php5.kiev.ua/manual/ru/function.array-search.html
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];
  }

?>
2009-10-02 03:22:12
http://php5.kiev.ua/manual/ru/function.array-search.html
for searching case insensitive better this:

<?php
array_search
(strtolower($element),array_map('strtolower',$array));
?>
2011-01-14 15:58:24
http://php5.kiev.ua/manual/ru/function.array-search.html
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($haystack0$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;
        }
    }
}
?>
2011-10-06 05:51:09
http://php5.kiev.ua/manual/ru/function.array-search.html
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_dumparray_search'xyz'$arr ) ); //bool
var_dumparray_search'xyz'$arrtrue ) ); //target

?>
2015-08-18 08:58:56
http://php5.kiev.ua/manual/ru/function.array-search.html
About searcing in multi-dimentional arrays; two notes on "xfoxawy at gmail dot com";

It perfectly searches through multi-dimentional arrays combined with array_column() (min php 5.5.0) but it may not return the values you'd expect.

<?php array_search($needlearray_column($array'key')); ?>

Since array_column() will produce a resulting array; it won't preserve your multi-dimentional array's keys. So if you check against your keys, it will fail.

For example;

<?php
$people 
= array(
 
=> array(
   
'name' => 'John',
   
'fav_color' => 'green'
 
),
 
5=> array(
   
'name' => 'Samuel',
   
'fav_color' => 'blue'
 
)
);

$found_key array_search('blue'array_column($people'fav_color'));
?>

Here, you could expect that the $found_key would be "5" but it's NOT. It will be 1. Since it's the second element of the produced array by the array_column() function.

Secondly, if your array is big, I would recommend you to first assign a new variable so that it wouldn't call array_column() for each element it searches. For a better performance, you could do;

<?php
$colors 
array_column($people'fav_color');
$found_key array_search('blue'$colors);
?>
2017-03-10 17:04:22
http://php5.kiev.ua/manual/ru/function.array-search.html
Despite PHP's amazing assortment of array functions and juggling maneuvers, I found myself needing a way to get the FULL array key mapping to a specific value. This function does that, and returns an array of the appropriate keys to get to said (first) value occurrence.

function array_recursive_search_key_map($needle, $haystack) {
    foreach($haystack as $first_level_key=>$value) {
        if ($needle === $value) {
            return array($first_level_key);
        } elseif (is_array($value)) {
            $callback = array_recursive_search_key_map($needle, $value);
            if ($callback) {
                return array_merge(array($first_level_key), $callback);
            }
        }
    }
    return false;
}

usage example:
-------------------

$nested_array = $sample_array = array(
    'a' => array(
        'one' => array ('aaa' => 'apple', 'bbb' => 'berry', 'ccc' => 'cantalope'),
        'two' => array ('ddd' => 'dog', 'eee' => 'elephant', 'fff' => 'fox')
    ),
    'b' => array(
        'three' => array ('ggg' => 'glad', 'hhh' => 'happy', 'iii' => 'insane'),
        'four' => array ('jjj' => 'jim', 'kkk' => 'kim', 'lll' => 'liam')
    ),
    'c' => array(
        'five' => array ('mmm' => 'mow', 'nnn' => 'no', 'ooo' => 'ohh'),
        'six' => array ('ppp' => 'pidgeon', 'qqq' => 'quail', 'rrr' => 'rooster')
    )
);

$search_value = 'insane';

$array_keymap = array_recursive_search_key_map($search_value, $nested_array);

var_dump($array_keymap);
// Outputs:
// array(3) {
// [0]=>
//  string(1) "b"
//  [1]=>
//  string(5) "three"
//  [2]=>
//  string(3) "iii"
//}

----------------------------------------------

But again, with the above solution, PHP again falls short on how to dynamically access a specific element's value within the nested array. For that, I wrote a 2nd function to pull the value that was mapped above.

function array_get_nested_value($keymap, $array)
{
    $nest_depth = sizeof($keymap);
    $value = $array;
    for ($i = 0; $i < $nest_depth; $i++) {
        $value = $value[$keymap[$i]];
    }

    return $value;
}

usage example:
-------------------
echo array_get_nested_value($array_keymap, $nested_array);   // insane
2018-01-19 00:18:35
http://php5.kiev.ua/manual/ru/function.array-search.html
Beware when using array_search to a mix of string and integer where prefixes of keys may collide, as in my case I have encountered the following situation:

Assume you have the following array:
<?php
$arr 
= [
           
=> 'index 0',
           
=> 'index 1',
           
=> 'index 2',
           
'3anothersuffix' => 'index 3'
];

$index1 array_search('3'array_keys($arr)); // 2
$index2 array_search('3anothersuffix'array_keys($arr)); //2
?>

$index1 and $index2 will be the same

after using strict type search:

<?php
$index1 
array_search('3'array_keys($arr), true); // false
$index2 array_search('3anothersuffix'array_keys($arr), true);  //3
?>

it will not find $index1 at all while returning a correct value for $index2;
2020-04-28 20:41:00
http://php5.kiev.ua/manual/ru/function.array-search.html
It's really important to check the return value is not false! I used array_search() to determine the index of an value to unset this value and then realized that $arr[false] === $arr[0] !

<?php
$arr 
= ['apple''banana'];

var_dump($arr[0] === 'apple'); // true
var_dump($arr[false] === $arr[0]); // true
var_dump($arr[false] === 'apple'); // true

unset($arr[array_search('banana'$arr)]); //index = 1
var_dump($arr);

// result
//   array(1) {
//     [0]=>
//     string(5) "apple"
//   }

unset($arr[array_search('peach'$arr)]); //not found, result is false
var_dump($arr);

// result
//   array(0) {
//   }
// because $arr[false] === $arr[0]
?>

So always check the return of array_search!
2020-05-08 11:08:56
http://php5.kiev.ua/manual/ru/function.array-search.html
Be careful!

<?php

var_dump
(array_search('needle', [ => ])); // int(0) (!)

var_dump(array_search('needle', [ => ], true)); // bool(false)

?>

But, in php 8

<?php

var_dump
(array_search('needle', [ => ])); // bool(false)

?>
2021-09-23 15:43:07
http://php5.kiev.ua/manual/ru/function.array-search.html

    Поддержать сайт на родительском проекте КГБ