Is there a short way of doing this?
if ((isset($a['key']) && ($a['key'] == 'value')) {
  echo 'equal';
  // more code
}
else {
  echo 'not equal';
  // more code
}
I need to test lots of values on an array that can or cannot exist. I feel that this method is too verbose.
I could remove the isset() and mute the notices... but then I feel dirty.
Edit:
Answering Jack's question: "Could you give an example how you would test lots of values in an array?"
example:
if (isset($_GET['action']) && $_GET['action'] == 'view') {
  //code
}
if (isset($_GET['filter']) && $_GET['filter'] == 'name') {
  //code
}
if (isset($_GET['sort']) && $_GET['sort'] == 'up') {
  //code
}
if (isset($_GET['tag']) && $_GET['tag'] == 'sometag') {
  //code
}
etc...
                For anyone still stumbling upon this question...
You could use PHP's coalescing operator:
if ( $a['key'] ?? false) {
  echo 'equal';
  // more code
}
else {
  echo 'not equal';
  // more code
}
See this question: using PHP's null coalescing operator on an array
I don't like to answer my own questions but I feel that the best and cleaner way to do this kind of checkings is to write a "helper funcion" like:
function iskeyval(&$a, $k, $v) {
  return isset($a['key']) && ($a['key'] == 'value');
}
and then:
if (iskeyval($a, 'key', 'value')) {
  ...
}
else {
  ...
}
                        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