Check for existence and assign

Posted on

Problem

Is there a smarter way to do the following without the $result variable and without the if-statements?

    ...
    $description = BIG ARRAY
    $result = array('error' => '', 'amounts' => array(5, 10, 25, 50));
    if (isset($description['error'])) $result['error'] = $description['error'];
    if (isset($description['amounts'])) $result['amounts'] = $description['amounts'];

    return $result;

Solution

To see if an array has a specific index you should use array_key_exists rather than isset.

In case you want default values, how about just assigning all the defaults at the same time:

$foo = function_call();
$result = array('error' => (array_key_exists('error', $description) ? $description['error'] : ''), ...);

Leave a Reply

Your email address will not be published. Required fields are marked *