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
.
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']);
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..