I have the following array($post_options
), it can appear in various guises, the key is dynamic:
It might be like this:
array(1) { [95]=> string(2) "25" }
It might be like this, the key can be anything:
array(1) { [05]=> string(2) "" }
I want to add a control statement that controls upon whether or not the value in the first key element has a value.
I have this code:
if (!isset($post_options[0])) {
// value is empty
var_dump($post_options);
}
else {
// value has value
echo 'Option Selected';
}
But this is not working, it returns true when the value is set and not set. What is the solution here? Thanks
So if the array appears like this (the value of the first key is empty):
array(1) { [05]=> string(2) "" }
I want to var_dump();
in this case
Depending on your exact requirements, there are three alternatives.
array_key_exists($key, $array)
This is the simplest option. It returns true
if the array has the given key, and otherwise returns false
.
isset($array[$key])
Slightly more strict than array_key_exists
since it also requires that the value assigned to the key is not null
.
!empty($array[$key])
(note the !
) This is the strictest option, as it requires the value to not be any empty value (i.e., not null
, false
, 0
, '0'
, etc).
There's some other options, again, depending on exact requirements. It looks to me that you are looking for the !empty
option, since it will (in particular) reject empty strings.
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