18

When using PHP, I find myself writing code like this a lot:

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

In Python, there is a dict.pop method that would let me do something similar in one statement, without a temporary variable:

return session.pop(AFTER_LOGIN_TARGET)

Is there a similar function or trick in PHP?

Dharman
  • 30,962
  • 25
  • 85
  • 135
LeafStorm
  • 3,057
  • 4
  • 24
  • 28

4 Answers4

13

I don't 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, e.g. $_SESSION:

return array_remove($_SESSION, 'AFTER_LOGIN_TARGET');

Short and Sweet

With PHP 7+ you can use the null coalescing operator to shorten this function greatly. You don't even need isset()!

function array_remove(array &$arr, $key) {
    $val = $arr[$key] ?? null;
    unset($arr[$key]);
    return $val;
}
David Harkness
  • 35,992
  • 10
  • 112
  • 134
  • 1
    @Eugene - `isset` will return `false` if the value is `null`, causing the function to leave the entry in the array. – David Harkness Jun 05 '12 at 14:07
  • I was talking about `array_key_exists`. `isset` would suffice. – Eugene Jun 05 '12 at 14:12
  • 3
    @Eugene - So was I. `php -r '$x["foo"] = null; var_dump(isset($x["foo"]));'` outputs `bool(false)`. `array_key_exists` is slightly slower, but it returns `true` even if the key is mapped to `null`. – David Harkness Jun 05 '12 at 14:23
  • Unset can be placed after the if-statement. If the key to be unset doesn't exist, no error occurs, not even a notice. So @Eugene is right, isset suffices. – aross Sep 23 '19 at 15:40
  • 1
    I posted a PHP7 solution 4 days earlier. https://stackoverflow.com/a/10898827/1000608 – aross Oct 01 '19 at 13:59
2

I think what you are looking for is array_slice()

$target = array_slice(
    $_SESSION, 
    array_search('AFTER_LOGIN_TARGET', $_SESSION),
    1
);
Peril Ravine
  • 1,142
  • 8
  • 12
2

Variant of this answer, using null coalesce.

function array_remove(array &$arr, $key) {
    $value = $arr[$key] ?? null;
    unset($arr[$key]);
    return $value;
}
aross
  • 3,325
  • 3
  • 34
  • 42
1

Why about a 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 asked for (try it a little, I haven't used php for many times :-])

Marco Pace
  • 3,820
  • 19
  • 38