How to delete a key and return the value from a PH

2019-01-27 16:17发布

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?

标签: php arrays pop
3条回答
家丑人穷心不美
2楼-- · 2019-01-27 16:39

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

查看更多
该账号已被封号
3楼-- · 2019-01-27 16:41

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');
查看更多
何必那么认真
4楼-- · 2019-01-27 16:46

I think what you are looking for is array_slice()

$target = array_slice(
    $_SESSION, 
    array_search('AFTER_LOGIN_TARGET', $_SESSION),
    1
);
查看更多
登录 后发表回答