2

Possible Duplicate:
Split into two variables?

I have a variable that will output two words. I need a way to split this data into two separate words, and specify a new variable for each separated word. For example:

$request->post['colors']

If the output is string "blue green", I need to split those two colors into separate variables, one for blue and one for green, ...eg $color_one for blue, and $color_two for green.

0

2 Answers 2

6

explode() them on the space and capture the two resulting array components with list()

list($color1, $color2) = explode(" ", $request->post['colors']);
echo "Color1: $color1, Color2: $color2";

// If an unknown number are expected, trap it in an array variable instead
// of capturing it with list()
$colors = explode(" ", $request->post['colors']);
echo $colors[0] . " " . $colors[1];

If you cannot guarantee one single space separates them, use preg_split() instead:

// If $request->post['colors'] has multiple spaces like "blue    green"
list($color1, $color2) = preg_split("/\s+/", $request->post['colors']);
Sign up to request clarification or add additional context in comments.

3 Comments

That works a treat! Thanks a lot for that. Also, what if the output is blue green yellow (and so on)? Would it simply take the first two words for the variables?
@ASmith If you don't know there will be only two, don't use list(). Instead capture in an array variable. See changes above.
Thanks for the great help and advice.
3

You can also use an array with explode too:

//store your colors in a variable
$colors=" blue green yellow pink purple   ";

//this will remove all the space chars from the end and the start of your string
$colors=trim ($colors);
$pieces = explode(" ", $colors);
//store your colors in the array, each color is seperated by the space

//if you don't know how many colors you have you can loop the with foreach

$i=1;
foreach ($pieces as $value) {
     echo "Color number: ".$i." is: " .$value;
     $i++;

}
//output: Color number: 1 is: blue
//        Color number: 2 is: green etc.. 

2 Comments

Thanks for the great help and advice.
You welcome ,my pleasure to help

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.