Skip to content
Advertisement

explode an array of delimited strings into two arrays

I have the following array:

JavaScript

that I need to split into two arrays using "-" as delimiter:

JavaScript

and

JavaScript

Is there anything like array_explode that does what I want? or a combination of php array functions? I’d like to do this without going through my own for/each loop, if possible, or at least minimize having to reinvent the wheel when something (pseudo)in-built is already out there. I already did this with a for loop. But I can’t shake the feeling that there’s a more elegant way that smartly uses array functions or anything of that kind. Thanks so much, guys.

Additional info:

Not sure if it matters, but I’m actually after the unique values in the resulting two arrays:

JavaScript

and

JavaScript

The unique values don’t need to be sorted, the keys may be preserved or not, and the legal values of the first array range from 0 to 23, while those of the second 1 to 7. However it’s possible to have values other than these (0 to 23 and 1 to 7 or even undelimited stray strings or other data types beyond my control), which I would definitely want to throw out.

Advertisement

Answer

The magic bullet you’re looking for is array_reduce(), e.g. (PHP 5.3+):

JavaScript

You can see it in action here.

With PHP <5.3 you’ll have to declare the function ahead of time:

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