Skip to content
Advertisement

Split flat array into grouped subarrays containing values from consecutive key in the input array

I have an array from array_diff function and it looks like below:

JavaScript

As you can see, we have a gap between the keys #3 and #5 (i.e. there is no key #4). How can I split that array into 2 parts, or maybe more if there are more gaps? The expected output would be:

JavaScript

Advertisement

Answer

You can use old_key,new_key concept to check that there difference is 1 or not? if not then create new index inside you result array otherwise add the values on same index:-

JavaScript

https://3v4l.org/Yl9rp

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement