Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Better" way to write this?

Tags:

php

Is there a better (ie, more readable) way to write this?

if (isset($input_vars['directive']) && $input_vars['directive'] == 'edit') {
like image 764
Glen Solsberry Avatar asked May 06 '10 18:05

Glen Solsberry


2 Answers

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.

like image 163
Sasha Chedygov Avatar answered Oct 11 '22 03:10

Sasha Chedygov


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.

like image 29
Alexander Kogtenkov Avatar answered Oct 11 '22 03:10

Alexander Kogtenkov