I have a normal, boring old array which has a lot of data in it. Let’s say the array is structured like this:
$myArray = array( 'a','b','c','START','d','e','f','END' );
Now, I need to select only the values that come after START, but before END. So, in this example, I need to select the values ‘d’, ‘e’, and ‘f’.
Here’s the tricky part; START will always exist, however END may or may not (this is how the data is returned from the server). If START and END both exist, then I just need the values inbetween the 2. if only START exists, then just select all the values from START until the end of the array. ‘START’ does not have a fixed index; its location changes depending on the data supplied from the server.
So what would be quick, relatively painless way to rip out these values in between 2 specified values, and then save them to a new array?
EDIT: The only implementation I was able to get functioning was the one provided by @nickb, further down in the comments. I have added it to this OP for ease of use for others.
array_shift( $array[0]); // Get rid of the 'count' element
$start = array_search( 'registered:current', $array[0], true);
$end = array_search( 'END', $array[0], true); // Change 'END' to whatever it is
$return = array_slice( $array[0], $start + 1, ($end ? ($end - $start - 1) : null));
How about this?
If
'END'isn’t found,array_search()will return false, which causes the the 3rd parameter toarray_slice()to be set tonull, returning the remaining elements in the array, starting at'START'. But if'END'is found, you’ll get an array containing the elements between'START'and'END', as seen in this demo.Edit: Here is a simpler implementation that uses the indexes directly, which is based on Matt’s edit with some tweaks to make it not include the delimiter:
Edit: Final implementation: