- How can I check if an array element exists?
- 8 Answers 8
- array_key_exists
- Parameters
- Return Values
- Examples
- Notes
- See Also
- User Contributed Notes 3 notes
- array_key_exists
- Список параметров
- Возвращаемые значения
- Примеры
- Примечания
- Смотрите также
- Check if an index exists in array in PHP
- Method 1: Using array_key_exists() function
- Frequently Asked:
- Method 2: Using isset() function
- Summary
- Related posts:
- Share your love
- Leave a Comment Cancel Reply
- Terms of Use
- Disclaimer
How can I check if an array element exists?
Of course, the first time I want an instance, $instances will not know the key. I guess my check for available instance is wrong?
8 Answers 8
You can use either the language construct isset , or the function array_key_exists .
isset should be a bit faster (as it’s not a function), but will return false if the element exists and has the value NULL .
For example, considering this array :
$a = array( 123 => 'glop', 456 => null, );
And those three tests, relying on isset :
var_dump(isset($a[123])); var_dump(isset($a[456])); var_dump(isset($a[789]));
The first one will get you (the element exists, and is not null) :
While the second one will get you (the element exists, but is null) :
And the last one will get you (the element doesn’t exist) :
On the other hand, using array_key_exists like this :
var_dump(array_key_exists(123, $a)); var_dump(array_key_exists(456, $a)); var_dump(array_key_exists(789, $a));
boolean true boolean true boolean false
Because, in the two first cases, the element exists — even if it’s null in the second case. And, of course, in the third case, it doesn’t exist.
For situations such as yours, I generally use isset , considering I’m never in the second case. But choosing which one to use is now up to you 😉
For instance, your code could become something like this :
if (!isset(self::$instances[$instanceKey]))
I have to complain ’cause isset is typo-unsafe. Called $form = [1 => 5]; var_dump(isset($from[1])); returns false since $from does not exist and you aren’t even notified by E_NOTICE . Slower, but safer array_key_exists do the thing for me.
array_key_exists() is SLOW compared to isset(). A combination of these two (see below code) would help.
It takes the performance advantage of isset() while maintaining the correct checking result (i.e. return TRUE even when the array element is NULL)
if (isset($a['element']) || array_key_exists('element', $a)) < //the element exists in the array. write your code here. >
The benchmarking comparison: (extracted from below blog posts).
array_key_exists() only : 205 ms isset() only : 35ms isset() || array_key_exists() : 48ms
And, isset is also misleading. Why would a keyword named «is set» return false when a variable, or an array position, is actually set — even though it is set to null?
You can use the function array_key_exists to do that.
$a=array("a"=>"Dog","b"=>"Cat"); if (array_key_exists("a",$a)) < echo "Key exists!"; >else
You can use isset() for this very thing.
$myArr = array("Name" => "Jonathan"); print (isset($myArr["Name"])) ? "Exists" : "Doesn't Exist" ;
According to the PHP manual you can do this in two ways. It depends what you need to check.
If you want to check if the given key or index exists in the array use array_key_exists
1, 'second' => 4); if (array_key_exists('first', $search_array)) < echo "The 'first' element is in the array"; >?>
If you want to check if a value exists in an array use in_array
You want to use the array_key_exists function.
A little anecdote to illustrate the use of array_key_exists .
// A programmer walked through the parking lot in search of his car // When he neared it, he reached for his pocket to grab his array of keys $keyChain = array( 'office-door' => unlockOffice(), 'home-key' => unlockSmallApartment(), 'wifes-mercedes' => unusedKeyAfterDivorce(), 'safety-deposit-box' => uselessKeyForEmptyBox(), 'rusto-old-car' => unlockOldBarrel(), ); // He tried and tried but couldn't find the right key for his car // And so he wondered if he had the right key with him. // To determine this he used array_key_exists if (array_key_exists('rusty-old-car', $keyChain))
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» ;
>
?>?php
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 );
?php
// 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);
- Array Functions
- array_change_key_case
- array_chunk
- array_column
- array_combine
- array_count_values
- array_diff_assoc
- array_diff_key
- array_diff_uassoc
- array_diff_ukey
- array_diff
- array_fill_keys
- array_fill
- array_filter
- array_flip
- array_intersect_assoc
- array_intersect_key
- array_intersect_uassoc
- array_intersect_ukey
- array_intersect
- array_is_list
- array_key_exists
- array_key_first
- array_key_last
- array_keys
- array_map
- array_merge_recursive
- array_merge
- array_multisort
- array_pad
- array_pop
- array_product
- array_push
- array_rand
- array_reduce
- array_replace_recursive
- array_replace
- array_reverse
- array_search
- array_shift
- array_slice
- array_splice
- array_sum
- array_udiff_assoc
- array_udiff_uassoc
- array_udiff
- array_uintersect_assoc
- array_uintersect_uassoc
- array_uintersect
- array_unique
- array_unshift
- array_values
- array_walk_recursive
- array_walk
- array
- arsort
- asort
- compact
- count
- current
- end
- extract
- in_array
- key_exists
- key
- krsort
- ksort
- list
- natcasesort
- natsort
- next
- pos
- prev
- range
- reset
- rsort
- shuffle
- sizeof
- sort
- uasort
- uksort
- usort
- each
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’.» ;
>
?>?phpПример #2 array_key_exists() и isset()
isset() не возвращает TRUE для ключей массива, указывающих на NULL , а array_key_exists() возвращает.
$search_array = array( ‘first’ => null , ‘second’ => 4 );
?php
// возвращает 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() — Проверяет, содержит ли объект или класс указанный атрибут
Check if an index exists in array in PHP
This tutorial will discuss about unique ways to check if an index exists in array in php.
Table Of Contents
Method 1: Using array_key_exists() function
The array_key_exists() function in PHP accepts an index/key and an array as arguments. It checks if the given array contains the given key or index. If yes, then it returns true, otherwise it returns false.
We can use this to check if a given index is valid or not i.e. it exists in the array or not.
Let’s see the complete example,
Frequently Asked:
The given Index exists in the array
Method 2: Using isset() function
Select element at given index from the array i.e. $arr[$index] , and then pass it to the isset() function, to check if this is declared or not. If it is set and has any value other then null, then it will return true. This way we can check if an index is valid or not for an array .
Let’s see the complete example,
The given Index exists in the array
Summary
We learned two ways to check if an index exists in an array or not.
Related posts:
Share your love
Leave a Comment Cancel Reply
This site uses Akismet to reduce spam. Learn how your comment data is processed.
Terms of Use
Disclaimer
Copyright © 2023 thisPointer
To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.