Array key exist function in php

PHP array_key_exists() Function

PHP array_key_exists() function is used to check whether a specific key or index is present inside an array or not.” The function returns TRUE if the specified key is found in the array; otherwise returns FALSE.

Syntax

array_key_exists(key, array)

Parameters

  1. key: It is the value of the key to be checked.
  2. array: It is an input array in which the key will be checked.

Return value

The function returns a boolean value, i.e., TRUE and FALSE, depending on whether the key is present in the array.

Example 1: How to Use PHP array_key_exists() function

  $arr = array("eleven" => 11, "dustin" => 21, "will" => 30, "nancy" => 40); if (array_key_exists("dustin", $arr))   echo "Key exists!"; > else   echo "Key does not exist!"; >

Example 2: Checking the indexed array keys

To check indexed array keys in PHP, use the array_key_exists() function. Let’s check if the integer key “0” exists in an array.

  $arr = array("eleven", "dustin", "will", "nancy"); if (array_key_exists(2, $arr))   echo "Key exists!"; > else   echo "Key does not exist!"; > 

Example 3: Compare Performance array_key_exists with isset()

To take the performance advantage of isset() while correctly detecting the NULL element.

Benchmark (100000 runs): array_key_exists(): 205 ms is_set(): 35ms isset() || array_key_exists(): 48ms

The above note on this page states that the isset() is significantly faster than array_key_exists(). It may be true except for one small hitch.

 $eddie = array(); $eddie['broke'] = NULL; var_dump(isset($eddie['broke'])); var_dump(array_key_exists('broke', $eddie)); 

Example 4: Passing an empty array

Passing an empty array to the array_key_exists() function won’t return anything because no key exists.

  $arr = array(); if (array_key_exists(0, $arr))   echo "Key exists!"; > else   echo "Key does not exist!"; > 

If an array passed to the array_key_exists() function is NULL, the return value will also be NULL.

The way the array_key_exists() function handles null, float, bool, and ‘integer-representing string’ keys is inconsistent in the case of boolean and float, with how these are converted when used as array offset.

Источник

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

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