patternphpMinor
Fetching an array value and removing it
Viewed 0 times
removingarrayandvaluefetching
Problem
So I have this array:
which could also be
Can the following code be improved into one line?
$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']);Solution
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 dounset($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.Code Snippets
if(isset($arr['d'])) $something = $arr['d'];
unset($arr['d']);if(isset($arr['d']))
{
$something = $arr['d'];
unset($arr['d']);
}unset($arr['d']);if (isset($arr['d']) && ($something = $arr['d']) !== null) unset($ar['d']);Context
StackExchange Code Review Q#3113, answer score: 4
Revisions (0)
No revisions yet.