Splitting up a string in PHP with every blank space

See explode

// Example 1
$pizza  = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2

Yes explode will do every thing for you and foreach can be used to retrieve the values from the array again. Your complete code will be something like following one:

$str = "foo bar php js";
$arr =  explode(" ", $str);

//print all the value which are in the array
foreach($arr as $v){
    echo $v;
}

Hope this will help you.


Daniel has already posted about the splitting part, let me add the checking for space part also.

$pizza  = "piece1 piece2 piece3 piece4 piece5 piece6";
$pizza = trim($pizza);

if(strpos($pizza, " ") !== false)

    $pieces = explode(" ", $pizza);
    echo $pieces[0]; // piece1
    echo $pieces[1]; // piece2

}else{

    echo $pizza;

}

Tags:

Php

String