Php найти ключ элемент в массиве

Замечание:

Если needle является строкой, сравнение происходит с учётом регистра.

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

Возвращаемые значения

Возвращает ключ для needle , если он был найден в массиве, иначе false .

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

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

Примеры

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

$array = array( 0 => ‘blue’ , 1 => ‘red’ , 2 => ‘green’ , 3 => ‘red’ );

$key = array_search ( ‘green’ , $array ); // $key = 2;
$key = array_search ( ‘red’ , $array ); // $key = 1;
?>

Смотрите также

  • array_keys() — Возвращает все или некоторое подмножество ключей массива
  • array_values() — Выбирает все значения массива
  • array_key_exists() — Проверяет, присутствует ли в массиве указанный ключ или индекс
  • in_array() — Проверяет, присутствует ли в массиве значение

User Contributed Notes 16 notes

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.

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.

$people = array(
2 => 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;

$colors = array_column ( $people , ‘fav_color’ );
$found_key = array_search ( ‘blue’ , $colors );
?>

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:

$code = array( «a» , «b» , «a» , «c» , «a» , «b» , «b» ); // infamous abacabb mortal kombat code 😛

// 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 ]);
>
?>

for searching case insensitive better this:

array_search ( strtolower ( $element ), array_map ( ‘strtolower’ , $array ));
?>

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

var_dump ( array_search ( ‘needle’ , [ 0 => 0 ], true )); // bool(false)

var_dump ( array_search ( ‘needle’ , [ 0 => 0 ])); // bool(false)

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:

$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
?>

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;
>

$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’)
)
);

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

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]];
>

usage example:
——————-
echo array_get_nested_value($array_keymap, $nested_array); // insane

Источник

array_key_exists

Функция array_key_exists() возвращает TRUE , если в массиве присутствует указанный ключ key . Параметр key может быть любым значением, которое подходит для индекса массива.

Список параметров

Массив с проверяемыми ключами

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Примеры

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

$search_array = array( ‘first’ => 1 , ‘second’ => 4 );
if ( array_key_exists ( ‘first’ , $search_array )) echo «Массив содержит элемент ‘first’.» ;
>
?>

Пример #2 array_key_exists() и isset()

isset() не возвращает TRUE для ключей массива, указывающих на NULL , а array_key_exists() возвращает.

$search_array = array( ‘first’ => null , ‘second’ => 4 );

// возвращает false
isset( $search_array [ ‘first’ ]);

// возвращает true
array_key_exists ( ‘first’ , $search_array );
?>

Примечания

Замечание:

Для обратной совместимости может быть использован следующий устаревший псевдоним: key_exists()

Замечание:

По причинам обратной совместимости array_key_exists() возвращает TRUE , если key является свойством объекта, переданным в качестве параметра array . На это поведение не стоит полагаться, и перед использованием данной функции необходимо проверять, что параметр array имеет тип array .

Чтобы проверить, содержит ли объект какое-либо свойство, используйте функцию property_exists() .

Смотрите также

  • isset() — Определяет, была ли установлена переменная значением отличным от NULL
  • array_keys() — Возвращает все или некоторое подмножество ключей массива
  • in_array() — Проверяет, присутствует ли в массиве значение
  • property_exists() — Проверяет, содержит ли объект или класс указанный атрибут

Источник

array_key_exists

array_key_exists() returns true if the given key is set in the array. key can be any value possible for an array index.

Parameters

An array with keys to check.

Return Values

Returns true on success or false on failure.

Note:

array_key_exists() will search for the keys in the first dimension only. Nested keys in multidimensional arrays will not be found.

Examples

Example #1 array_key_exists() example

$search_array = array( ‘first’ => 1 , ‘second’ => 4 );
if ( array_key_exists ( ‘first’ , $search_array )) echo «The ‘first’ element is in the array» ;
>
?>

Example #2 array_key_exists() vs isset()

isset() does not return true for array keys that correspond to a null value, while array_key_exists() does.

$search_array = array( ‘first’ => null , ‘second’ => 4 );

// returns false
isset( $search_array [ ‘first’ ]);

// returns true
array_key_exists ( ‘first’ , $search_array );
?>

Notes

Note:

For backward compatibility reasons, array_key_exists() will also return true if key is a property defined within an object given as array . This behaviour is deprecated as of PHP 7.4.0, and removed as of PHP 8.0.0.

To check whether a property exists in an object, property_exists() should be used.

See Also

  • isset() — Determine if a variable is declared and is different than null
  • array_keys() — Return all the keys or a subset of the keys of an array
  • in_array() — Checks if a value exists in an array
  • property_exists() — Checks if the object or class has a property

User Contributed Notes 3 notes

When you want to check multiple array keys:

$array = [];
$array [ ‘a’ ] = » ;
$array [ ‘b’ ] = » ;
$array [ ‘c’ ] = » ;
$array [ ‘d’ ] = » ;
$array [ ‘e’ ] = » ;

// all given keys a,b,c exists in the supplied array
var_dump ( array_keys_exists ([ ‘a’ , ‘b’ , ‘c’ ], $array )); // bool(true)

function array_keys_exists (array $keys , array $array ): bool
$diff = array_diff_key ( array_flip ( $keys ), $array );
return count ( $diff ) === 0 ;
>

In PHP7+ to find if a value is set in a multidimensional array with a fixed number of dimensions, simply use the Null Coalescing Operator: ??

So for a three dimensional array where you are not sure about any of the keys actually existing

// use:
$exists = array_key_exists ( $key3 , $arr [ $key1 ][ $key2 ]??[]) ;

I took hours for me to debug, and I finally recognized that,

You have to reset the $array before using array_key_exists
reset($array);
array_key_exists($needle,$array);

Оцените статью