Search code examples
phparraysexplode

Explode a delimited string and print the elements as part of a larger string


I am stuck and was hoping someone could help me out.

I have a multiple selection list that looks like this:

<select name='verseData[]' size=5 multiple>
    <option value='pig:oink'>Pig
    <option value='duck:quack'>Duck
    <option value='cow:moo'>Cow
    <option value='sheep:baa'>Sheep
    <option value='horse:neigh'>Horse
    <option value='dog:woof'>Dog
    <option value='cat:meow'>Cat
    <option value='rooster:cock-a-doodle-doo'>Rooster

I want to separate the animal and animal noise. I also want to be able to refer to them so that you could write a sentence using to variables like:

The $animal makes the sound $noise.

The dog makes the sound woof.


Solution

  • Here you go:

        foreach($_POST['verseData'] as $value){
            list($animal, $noise) = explode(":", $value);
            echo "The $animal makes the sound $noise";
        }