Parse string containing two numbers and assign them to two variables
$pos
contains two numbers delimited by a space in one string.
$pos = 98.9 100.2
How can I split this into 2 variables? I obviously have to check for the space in between.
I would like to have two variables afterwar开发者_Go百科ds:
$number1 = 98.9
$number2 = 100.2
list($number1, $number2) = explode(' ', $pos);
However, make sure the string has the right format before doing this.
If it is always a space, then check
array explode ( string $delimiter , string $string [, int $limit ] )
And in your case you have
$foo = "1.2 3.4 invalidfoo"
$bits = explode(" ",$foo);
which gives you an array:
echo 0+$bits[0];
echo 0+$bits[1];
echo 0+$bits[3];
Use +0 to force the cast :)
You could use:
$pos = "98.9 100.2";
$vals = preg_split("/[\s]+/", $pos);
list($number1, $number2) = $vals;
Using sscanf()
instead of general-use string splitting functions like explode()
or preg_split()
, you can instantly data-type the isolated values.
For the sample string, using %f
twice will extract the space-delimited values and cast the two numeric values as floats/doubles.
Code: (Demo)
$pos = '98.9 100.2';
sscanf($pos, '%f %f', $number1, $number2);
var_dump($number1);
echo "\n";
var_dump($number2);
Output:
float(98.9)
float(100.2)
There is an alternative syntax which will act the same way, but return the values as an array. (Demo)
$pos = '98.9 100.2';
var_dump(sscanf($pos, '%f %f'));
Output:
array(2) {
[0]=>
float(98.9)
[1]=>
float(100.2)
}
精彩评论