Quantcast
Channel: How to check if multiple array keys exists - Stack Overflow
Viewing all articles
Browse latest Browse all 22

Answer by Sven for How to check if multiple array keys exists

$
0
0

If you have something like this:

$stuff = array();$stuff[0] = array('story' => 'A story', 'message' => 'in a bottle');$stuff[1] = array('story' => 'Foo');

You could simply count():

foreach ($stuff as $value) {  if (count($value) == 2) {    // story and message  } else {    // only story  }}

This only works if you know for sure that you ONLY have these array keys, and nothing else.

Using array_key_exists() only supports checking one key at a time, so you will need to check both seperately:

foreach ($stuff as $value) {  if (array_key_exists('story', $value) && array_key_exists('message', $value) {    // story and message  } else {    // either one or both keys missing  }}

array_key_exists() returns true if the key is present in the array, but it is a real function and a lot to type. The language construct isset() will almost do the same, except if the tested value is NULL:

foreach ($stuff as $value) {  if (isset($value['story']) && isset($value['message']) {    // story and message  } else {    // either one or both keys missing  }}

Additionally isset allows to check multiple variables at once:

foreach ($stuff as $value) {  if (isset($value['story'], $value['message']) {    // story and message  } else {    // either one or both keys missing  }}

Now, to optimize the test for stuff that is set, you'd better use this "if":

foreach ($stuff as $value) {  if (isset($value['story']) {    if (isset($value['message']) {      // story and message    } else {      // only story    }  } else {    // No story - but message not checked  }}

Viewing all articles
Browse latest Browse all 22

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>