I have a string of numbers "2,3,5". I also have an array
[0] pens
[1] paper
[2] pencils
[3] lead
[4] trashcans
[5] cars
I'd like to change "2,3,5" to "pencils,lead,cars"
Is there some simple way to do this or only a brute force method?
CodePudding user response:
You can do this with a one-liner, but it is (IMHO) ugly and I don't know if I'd recommend this in production because I don't know if there's some weird edge cases it doesn't account for,
- explode on comma
- swap values for keys
- compute intersection
- re-join
implode(',', array_intersect_key($array, array_flip(explode(',', $string))));
Demo: https://3v4l.org/HQ7GB