Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shorthand to check value in array

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...
like image 244
Peter Avatar asked Nov 12 '12 18:11

Peter


2 Answers

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

like image 184
Fabien Snauwaert Avatar answered Sep 24 '22 06:09

Fabien Snauwaert


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 {
  ...
}
like image 25
Peter Avatar answered Sep 26 '22 06:09

Peter