0
\$\begingroup\$

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;
\$\endgroup\$
2
  • 1
    \$\begingroup\$ Can you explain a bit more what you're trying to do? $result has defaults that you're trying to overwrite with values from $description if they exist and are non-null? Are error and amounts the only fields? \$\endgroup\$
    – Corbin
    Jun 18 '13 at 6:44
  • \$\begingroup\$ @Corbin: yes, exactly. \$\endgroup\$
    – Fu86
    Jun 18 '13 at 7:53
2
\$\begingroup\$

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'] : ''), ...);
\$\endgroup\$
7
  • \$\begingroup\$ Thanks for the tip with the in_array. I thought thats internally the same as isset(). But the function_call() call does not work this way. Where do I put the in_array/isset check? It returned bool, not the element. \$\endgroup\$
    – Fu86
    Jun 18 '13 at 7:58
  • \$\begingroup\$ $a = false || 7; echo $a; gives me "true". I think, the boolean operators here are handled the wrong way. I use PHP 5.4.16 \$\endgroup\$
    – Fu86
    Jun 18 '13 at 8:08
  • \$\begingroup\$ What do you mean by "does not work this way"? And the point of the code was to avoid the check completely. \$\endgroup\$
    – l0b0
    Jun 18 '13 at 8:10
  • \$\begingroup\$ Fixed syntax. \$\endgroup\$
    – l0b0
    Jun 18 '13 at 8:11
  • 1
    \$\begingroup\$ in_array does not do what you think it does. You're thinking of array_key_exists. in_array searches for a value, not a key. Also, array_key_exists and isset are not equivalent. (isset($arr[$key]) === array_key_exists($key, $arr) && $arr[$key] !== null) \$\endgroup\$
    – Corbin
    Jun 18 '13 at 9:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.