1

Is there a native PHP function for removing an element from an associative array, and returning the value?

Like unset() but with a return value, or array_shift() where you can specify the index to shift?

$element = unset($array['index']);

$element = array_shift($array, 'index');

I know it's easy to do, I'm just curious if there's an elegant one-liner for doing this.

3
  • 2
    Nope, the documentation does not show such a function. Commented Jan 4, 2019 at 12:36
  • You can buid a custom one with the and use it. Commented Jan 4, 2019 at 12:37
  • 1
    If you know the index, returning the value prior to unsetting should be a breeze. I'd use array_splice() Commented Jan 4, 2019 at 12:38

1 Answer 1

2

Looking quickly at the official PHP documentation, in the current version (7.2) doesn't have a function that removes and returns an element by the key.

But as you mentioned there are several ways to solve this problem. As you can see at: https://stackoverflow.com/a/10898827/4214312

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

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.