1

I have array:

$arr = array(
    'a' => 1,
    'b' => 2,
    'c' => 3
);

Is there built-in php function which gets array value by key and then removes element from this array?

I know array_shift and array_pop functions, but I need to get element by custom key, not first/last element. Something like:

$arr; // 'a'=>1, 'b'=>2, 'c'=>3
$elem = array_shift_key($arr, 'b');
echo $elem; // 2
$arr; // 'a'=>1, 'c'=>3
0

3 Answers 3

3

Not sure about native way, but this should work:

function shiftByKey($key, &$array) {
    if (!array_key_exists($key, $array)) {
        return false;
    }

    $tmp = $array[$key];
    unset($array[$key]);

    return $tmp;
}

Edit: Updated it so that array is passed by reference. Else your array stays the same.

Sign up to request clarification or add additional context in comments.

1 Comment

Ok, thanks! This function works as I need. I thought what exists built-in php function for this common operation in daily tasks. I think that now the best way is continue using standard access operator [] and unset syntax..
3

As far as I'm aware there's nothing that comes close to that. Can be written easily though:

function array_shift_key(array &$array, $key) {
    $value = $array[$key];
    unset($array[$key]);
    return $value;
}

If you care, validate first whether the key exists in the array and do something according to your error handling philosophy if it doesn't. Otherwise you'll simply get a standard PHP notice for non-existing keys.

Comments

0
function array_shift_key(array &$input, $key) {
    $value = null;

    // Probably key presents with null value
    if (isset($input[$key]) || array_key_exists($key, $input)) {
        $value = $input[$key];
        unset($input[$key]);
    }

    return $value;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.