# Check for existence and assign

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;

• 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? – Corbin Jun 18 '13 at 6:44
• @Corbin: yes, exactly. – Fu86 Jun 18 '13 at 7:53

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'] : ''), ...);

• 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. – Fu86 Jun 18 '13 at 7:58
• $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 – Fu86 Jun 18 '13 at 8:08
• What do you mean by "does not work this way"? And the point of the code was to avoid the check completely. – l0b0 Jun 18 '13 at 8:10
• Fixed syntax. – l0b0 Jun 18 '13 at 8:11
• 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) – Corbin Jun 18 '13 at 9:59