"how to delete a key and return the value from a php array?" Code Answer

2

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;
}
By HelloWorld123456789 on July 12 2022

Answers related to “how to delete a key and return the value from a php array?”

Only authorized users can answer the Search term. Please sign in first, or register a free account.