0

I want something that works like array_pop() or array_shift(), so it returns the removed element, but I'd like to specify by key which element to remove.

Example:

$arr = ['a' => 1, 'b' => 2, 'c' => 3]; 
$removed = array_remove($arr, 'b');

print_r($arr); // Outputs: Array(['a'] => 1, ['c'] => 3 )
print_r($removed); // Outputs: 2

Now I'am using

$arr = ['a' => 1, 'b' => 2, 'c' => 3]; 
$removed = $arr['b'];
unset($arr['b']);
5
  • If you go to the manual, you can go through the existing array functions and check if any of them does what you want. There aren't that many... Commented Mar 19, 2018 at 14:32
  • What's wrong with your current version? As it's only 2 lines long, it's hardly bloating your code. Commented Mar 19, 2018 at 14:36
  • No but it would be trivial to make array_remove. 3v4l.org/lhFMI Commented Mar 19, 2018 at 14:36
  • Check this answer - stackoverflow.com/questions/369602/… Commented Mar 19, 2018 at 14:39
  • I believe your solution is readable, the most performant and that there is not a reserved function for what you want. Commented Mar 22, 2018 at 14:35

1 Answer 1

1

array_splice() http://php.net/manual/en/function.array-splice.php Omit replacement.

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

1 Comment

That won't work with hash maps and the removed value is not returned. The second argument must be an integer and the return type is an array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.