Home » Php » PHP: Check if array key has value

PHP: Check if array key has value

Posted by: admin July 12, 2020 Leave a comment

Questions:

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

How to&Answers:

If you don’t know the first key of array – use array_keys, for example, to get all keys of your array.

$ar = array('95' => 'val');
$keys = array_keys($ar);
$first_item = $ar[$keys[0]]; 
var_dump($first_item);    // outputs: string(3) "val" 

Another option can be a current function, which will return you current element of an array. Considering that you don’t move array pointer, code can be:

$ar = array('95' => 'new_val', '02' => 'val2');
$cur = current($ar);
var_dump($cur);  // outputs: string(7) "new_val" 

After that you can use standard emptyfunction to check:

if (empty($cur))

or

if (empty($first_item))

Answer:

Depending on your exact requirements, there are three alternatives.

  1. array_key_exists($key, $array)
    This is the simplest option. It returns true if the array has the given key, and otherwise returns false.

  2. isset($array[$key])
    Slightly more strict than array_key_exists since it also requires that the value assigned to the key is not null.

  3. !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.

Answer:

try this

if (!isset($post_options[0])) {            // value is empty
    if(!empty($post_options[0])) {
          var_dump($post_options);          
    }           
}

Answer:

isset checks whether the array position exists or not, not whether it cointains or it doesn’t contain a value.

You better have a look at the empty function to do this

if (empty($post_options[0])) {
    // value is empty
    var_dump($post_options);
} else {
    // value has value
    echo 'Option Selected';
}

hope this helps