0

This is almost certainly a duplicate of this question but I guess my question is more about common conventions/best practices, given the answers there.

Example:

if(isset($this->_available[$option]['accepts_argument']) && $this->_available[$option]['accepts_argument']) {
  // do something
}

It's just ugly. But if I don't do the first check, I get a php NOTICE. Should I make sure the array key 'accepts_argument' always exists, and defaults to false? That way I could just test if it's true, instead of also testing if it exists?

Should I just not worry about the ugliness/verbosity ?

I'm noticing this pattern a lot in my code, and just wondering how people handle it. I'm currently using php 5.4, if that matters, but I could upgrade it if there's something fancy in 5.5+ that I could do.

Thanks

Community
  • 1
  • 1
Kevin
  • 1,489
  • 2
  • 20
  • 30

1 Answers1

0

Here's a function I use that can help you:

 /** todo handle numeric values
 * @param  array  $array      The array from which to get the value
 * @param  array  $parents    An array of parent keys of the value,
 *                            starting with the outermost key
 * @param  bool   $key_exists If given, an already defined variable
 *                            that is altered by reference
 * @return mixed              The requested nested value. Possibly NULL if the value
 *                            is NULL or not all nested parent keys exist.
 *                            $key_exists is altered by reference and is a Boolean
 *                            that indicates whether all nested parent keys
 *                            exist (TRUE) or not (FALSE).
 *                            This allows to distinguish between the two
 *                            possibilities when NULL is returned.
 */
function &getValue(array &$array, array $parents, &$key_exists = NULL)
{
    $ref = &$array;
    foreach ($parents as $parent) {
        if (is_array($ref) && array_key_exists($parent, $ref))
            $ref = &$ref[$parent];
        else {
            $key_exists = FALSE;
            $null = NULL;
            return $null;
        }
    }
    $key_exists = TRUE;
    return $ref;
}

It gets the value of an element in an array even if this array is nested. Return null if the path doesn't exist. Magic!

example:

$arr = [
    'path' => [
        'of' => [
            'nestedValue' => 'myValue',
        ],
    ],
];
print_r($arr);
echo getValue($arr, array('path', 'of', 'nestedValue'));
var_dump(getValue($arr, array('path', 'of', 'nowhere')));
Adam Sinclair
  • 1,654
  • 12
  • 15