How to delete a key and return the value from a PHP array?

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;
}

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 :-])

Tags:

Php

Arrays