Skip to content

Commit

Permalink
Adding array_take function.
Browse files Browse the repository at this point in the history
  • Loading branch information
maximkott committed Mar 6, 2016
1 parent 157467f commit c6df5f9
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 0 deletions.
7 changes: 7 additions & 0 deletions readme.md
Expand Up @@ -15,6 +15,7 @@
- [array_set](#array_set)
- [array_remove](#array_remove)
- [array_add](#array_add)
- [array_take](#array_take)
- [array_reset](#array_reset)
- [array_dot](#array_dot)
- [array_extend](#array_extend)
Expand Down Expand Up @@ -62,6 +63,12 @@ Add an element to the array at a specific location using the "dot" notation.

`array array_add(array &$array, mixed $key, mixed $value)`

#### array\_take

Get an element and remove it from the array using the "dot" notation.

`array array_take(array &$array, mixed $key, [, mixed $default = null])`

#### array\_reset

Reset all numerical indexes of an array (start from zero). Non-numerical indexes will stay untouched.
Expand Down
21 changes: 21 additions & 0 deletions src/array.php
Expand Up @@ -153,6 +153,27 @@ function array_add(array &$array, $key, $value) {
}
}

if ( ! function_exists('array_take')) {
/**
* Get an item and remove it from the array.
*
* @param array $array
* @param $key
* @param null $default
*
* @return mixed
*/
function array_take(array &$array, $key, $default = null) {
$value = array_get($array, $key, $default);

if (array_has($array, $key)) {
array_remove($array, $key);
}

return $value;
}
}

if ( ! function_exists('array_reset')) {
/**
* Reset all numerical indexes of an array (start from zero).
Expand Down
6 changes: 6 additions & 0 deletions tests/ArrayTest.php
Expand Up @@ -239,4 +239,10 @@ public function test_array_reset($expected, $array, $deep) {
public function test_array_add($expected, $array, $key, $value) {
$this->assertEquals($expected, array_add($array, $key, $value));
}

public function test_array_take() {
$array = ['foo' => ['bar' => 'baz']];
$this->assertEquals('baz', array_take($array, 'foo.bar'));
$this->assertEquals(['foo' => []], $array);
}
}

0 comments on commit c6df5f9

Please sign in to comment.