Is there a better (ie, more readable) way to write this?
if (isset($input_vars['directive']) && $input_vars['directive'] == 'edit') {
Not really, unfortunately. You could wrap this code in a function and simply call that every time you need this.
function compareArrayItem($array, $key, $value) {
return isset($array[$key]) && $array[$key] == $value;
}
if (compareArrayItem($input_vars, 'directive', 'edit')) {
// Do something
}
But that seems kind of pointless to me (and less readable than your original code). Or you could lower the error reporting level to not include E_NOTICE
so that you don't need the first expression at all.
error_reporting(E_ALL ^ E_NOTICE);
if ($input_vars['directive'] == 'edit') //...
But I wouldn't recommend doing this just for the sake of shortening your code.
If I were you, I'd just leave it alone. It's fine as-is.
If the set of allowed values in $input_vars
is known and the checks you mention are all over the place the following helper function will do:
function item ($array, $key) {
if (isset ($array [$key]))
return $array [$key];
else
return NULL; // Or use whatever is more appropriate
}
Then the original code can be changed to look like
if (item ($input_vars, 'directive') == 'edit') { ...
This is not only more readable, but also removes duplication: both array variable and key appear only once.
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