7
\$\begingroup\$

So I have this array:

$arr = ('a' => 343, 'b' => 34, 'c' => 65, 'd' => 465);

which could also be

$arr = ('a' => 343, 'b' => 34, 'c' => 65);

Can the following code be improved into one line?

if(isset($arr['d'])) $something = $arr['d'];
unset($arr['d']);
\$\endgroup\$
2
  • 1
    \$\begingroup\$ What is your goal? To always remove elements called 'd'? Or to have a maximum of 3 key / values? \$\endgroup\$
    – Arend
    Commented Jun 25, 2011 at 14:55
  • 1
    \$\begingroup\$ yes, to remove 'd' keys \$\endgroup\$
    – user815340
    Commented Jun 25, 2011 at 14:56

3 Answers 3

4
\$\begingroup\$
if(isset($arr['d'])) $something = $arr['d'];
unset($arr['d']);

Well... If arr['d'] is not set, then you don't need to unset it. So this will save an unnecessary call sometimes:

if(isset($arr['d']))
{
    $something = $arr['d'];
    unset($arr['d']);
}

If you don't care for $something, then you can just do

unset($arr['d']);

Which is then one line. You could also write

if (isset($arr['d']) && ($something = $arr['d']) !== null) unset($ar['d']);

That is one line as well, but will fail to do what you like if $something is null. And from the point of readability it's questionable whether this is an improvement.

\$\endgroup\$
2
\$\begingroup\$

No, there is no way to squash it into one line and keep it readable in any way.

$something = isset($arr['d'])
           ? $arr['d']
           : null;
unset($arr['d']);

This is just a minor enhancement, I know, but I think if one is familiar with the ternary operator its slightly better readable. At the end I don't think there is anything more optimizable.

\$\endgroup\$
0
\$\begingroup\$

No reason why you can't right your own function to do this, obviously the function itself is more than 1 line but will make it a lot easier to use if you're calling it multiple times in your project.

function getValue(&$array, $key) {
    $value = isset($array[$key]) ? $array[$key] : null;
    unset($array[$key]);
    return $value;
}

$arr = array('a' => 343, 'b' => 34, 'c' => 65, 'd' => 465);

$val = getValue($arr, 'd');

If you var_dump the two variables it will give you

// $val
int 465
// $arr
array
  'a' => int 343
  'b' => int 34
  'c' => int 65

If the key does not exist $val will simply be NULL.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.