Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Check if array key has value

Tags:

arrays

php

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

like image 737
Liam Fell Avatar asked Jan 29 '16 11:01

Liam Fell


1 Answers

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.

like image 129
Ken Wayne VanderLinde Avatar answered Sep 21 '22 22:09

Ken Wayne VanderLinde