Home > Back-end >  converting from a string of numbers to a string of values in php
converting from a string of numbers to a string of values in php

Time:12-11

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,

  1. explode on comma
  2. swap values for keys
  3. compute intersection
  4. re-join
implode(',', array_intersect_key($array, array_flip(explode(',', $string))));

Demo: https://3v4l.org/HQ7GB

  •  Tags:  
  • php
  • Related