How to remove a key and return a value from a PHP array?

When using PHP, I find that I am writing so much code:

$target = $_SESSION[AFTER_LOGIN_TARGET]; unset($_SESSION[AFTER_LOGIN_TARGET]); return $target; 

In Python, there is a dict.pop method that would allow me to do something similar in one of the statements without a temporary variable:

 return session.pop(AFTER_LOGIN_TARGET) 

Is there a similar feature or trick in PHP?

+11
arrays php pop
source share
4 answers

I do not see a built-in function for this, but you can easily create your own.

 /** * Removes an item from the array and returns its value. * * @param array $arr The input array * @param $key The key pointing to the desired value * @return The value mapped to $key or null if none */ function array_remove(array &$arr, $key) { if (array_key_exists($key, $arr)) { $val = $arr[$key]; unset($arr[$key]); return $val; } return null; } 

You can use it with any array, for example, $_SESSION :

 return array_remove($_SESSION, 'AFTER_LOGIN_TARGET'); 

Short and sweet

In PHP 7+, you can use the union operator of zeros to greatly reduce this feature. You don't even need isset() !

 function array_remove(array &$arr, $key) { $val = $arr[$key] ?? null; unset($arr[$key]); return $val; } 
+7
source share

Why about helper function? Something like that:

 function getAndRemoveFromSession ($varName) { $var = $_SESSION[$varName]; unset($_SESSION[$varName]); return $var; } 

So if you call

 $myVar = getAndRemoveFromSession ("AFTER_LOGIN_TARGET"); 

you have what you requested (try a little, I have not used php many times: -])

+1
source share

I think you are looking for array_slice ()

 $target = array_slice( $_SESSION, array_search('AFTER_LOGIN_TARGET', $_SESSION), 1 ); 
+1
source share

A variation of this answer using null coalesce.

 function array_remove(array &$arr, $key) { $value = $arr[$key] ?? null; unset($arr[$key]); return $value; } 
0
source share

All Articles