When coding php I try to avoid as many warnings as possible. There is one question that bugs me for quite some time now, regarding arrays.
When working with arrays and their values I often check for empty values first before I go to the "real work".
if(array_key_exists('bla', $array){
if( !empty($array['bla']) {
# do something
}
}
My Question is:
This is a lot of code for just checking if I have values to work with. Is there some shorter way to check a value within an array that may or may not exist?
The equivalent of isset($var) for a function return value is func() === null .
The isset() function is an inbuilt function in PHP that is used to determine if the variable is declared and its value is not equal to NULL. The empty() function is an inbuilt function in PHP that is used to check whether a variable is empty or not.
Difference between isset() and array_key_exists() Function: The main difference between isset() and array_key_exists() function is that the array_key_exists() function will definitely tells if a key exists in an array, whereas isset() will only return true if the key/variable exists and is not null.
PHP isset() vs.The is_null() function returns true if the value of a variable has been explicitly set to NULL . Otherwise, it simply returns false . On the other hand, isset() will return true as long as a variable is defined and its value is not NULL .
Don't use empty
unless you are sure that's what you want:
Returns
FALSE
ifvar
exists and has a non-empty, non-zero value. Otherwise returnsTRUE
.The following things are considered to be empty:
""
(an empty string)0
(0 as an integer)0.0
(0 as a float)"0"
(0 as a string)NULL
FALSE
array()
(an empty array)$var;
(a variable declared, but without a value)
The manual doesn't explicitly list the "if var
doesn't exist" cases, but here are a couple:
$array['undeclaredKey']
(an existing array, but key not declared)$undeclaredVar;
(a variable not declared)Usually the array_key_exists
check should suffice.
If you are checking for a non-empty value, then you can just use !empty($array['bla'])
.
You can also use isset($array['bla'])
, which returns false
when: 1) key is not defined OR 2) if the value stored for the key is null
. The only foolproof way to check if the array contains a key (even if its value is null) is to use array_key_exists()
.
The call to empty()
is safe even if the key exists (behaves like isset()
), so you don't have to protect it by the array_key_exists()
.
I am surprised this was not mentioned, but the shortest way fetch a value for a key without generating a warning/error is using the Error Control Operator:
// safely fetch from array, will return NULL when key doesn't exist
$value = @$array['bla'];
This allows you get the value for any key with the possibilty of its return value being null
if the key does not exist.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With