Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if array key exists and is truthy in same command?

Tags:

idioms

php

web

In JavaScript, one can check myObject.key to see wether the value is there (not undefined) and truthy.

if (myObject.key) ...

Is there a PHP equivalent? Or do I have to keep writing code such as isset(my_array['key']) && my_array['key'] to acheive the desired result? I feel it violates DRY and looks ugly.

like image 529
Aviv Cohn Avatar asked Sep 15 '25 02:09

Aviv Cohn


1 Answers

There are three "levels" of checking in php:

  1. array_key_exists($key, $array) - http://php.net/manual/en/function.array-key-exists.php

Checks if a key exists in an array. Returns true even if the value is null

  1. isset($array[$key]) - http://php.net/manual/en/function.isset.php

Check if a key exists and is not null - Returns true if the value exists and is not null, but it can be bool(false), int(0), string "" and so on.

  1. !empty($array[$key]) - http://php.net/manual/en/function.empty.php

Check if a key exists and is truthy, returns false for bool(false), int(0), non-existant keys and null, but true for bool(true), int(1), int(-1), string with length > 0 and so on. Actually the function it is empty(), but often used negated, too. This should be what you are searching for.

like image 84
clemens321 Avatar answered Sep 17 '25 16:09

clemens321