Re: [PHP-DEV] [RFC] [DISCUSSION] array_part()
Gustavo Lopes <glopes <at> nebm.ist.utl.pt>
2012-05-14 14:03:21 GMT
On Mon, 14 May 2012 15:41:25 +0200, Paul Dragoonis <dragoonis <at> gmail.com>
> Gustavo, why would I use array_part() if I could use array_slice() to get
> the parts of an array between two offsets.
Obviously, if you want to do something that array_slice() already does,
then you wouldn't have a lot of pressing reasons to use this instead. But
this is not a very interesting question.
On the other hand, if you're asking what are differences between this and
* array_slice() only does slicing at the level 1 (it has no
multidimensional slicing that would allow doing something like
array_column(), see https://github.com/php/php-src/pull/56 )
* array_slice() only operates in an 'index-as-offset' mode, which is less
efficient than 'index-as-key'. array_part() allows you to choose:
$arr = [-1 => 'a', 0 => 'b'];
array_slice($arr, 0, 1) // 'a'
array_slice($arr, -1, 1) // 'b'
array_part($arr, ) // 'a'
array_part($arr, [-1]) // 'b'
array_part($arr, [-1], true) // 'a'
* array_slice() has side-effects; it resets the internal array pointer.
* array_slice() can preserve keys, array_part() cannot because when
collapsing levels this would mean the possibility of overwriting elements.