Replacing array_slice

From: Date: Tue, 17 Jul 2018 04:11:16 +0000
Subject: Replacing array_slice
Groups: php.internals 
Request: Send a blank email to internals+get-102874@lists.php.net to get a copy of this message
Recently I've been scrutinizing array_slice. It's been painful. For instance, $preserve_keys is totally ignored for string keys. This was undocumented until Christoph integrated it 2-3 days ago (thanks, cmb). However, this is really not a good design decision: why have a parameter that is called preserve_keys if the data gets the final say, especially since there isn't any technical requirement for this? Here's another "fun" behavior: negative offsets whose absolute values are larger than the size of the array (eg the array has 3 elements and you pass an offset of -5) will shift the window to begin at zero instead of truncating the out-of-range values (which is what happens on the positive side). And another: $length is a length when it's a positive number, but it's an offset from the end when it's negative. You could perhaps convince me that when length is positive it's an offset from the $offset parameter. However, if you look at the design of slicing functions in other languages (eg Python, Ruby, JavaScript) they take beginning and ending offsets, not a beginning offset and a length. And another: it always iterates from the beginning of the array even if you are only interested in the last half (somewhat common for various algorithms that split things in half). Fixing array_slice would probably do more harm than good at this stage. Instead I would like to provide an alternative function that does not have all this baggage, and will have decent performance much of the time. The best ideas I have for names are not that great: - array_real_slice? - array_slice2? We could also split it into 2 functions, one that preserves keys and one that doesn't, instead of using a parameter. Any ideas there?

« previous php.internals (#102874) next »