'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 afterwards:
$number1 = 98.9
$number2 = 100.2
Solution 1:[1]
list($number1, $number2) = explode(' ', $pos);
However, make sure the string has the right format before doing this.
Solution 2:[2]
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 :)
Solution 3:[3]
You could use:
$pos = "98.9 100.2";
$vals = preg_split("/[\s]+/", $pos);
list($number1, $number2) = $vals;
Solution 4:[4]
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)
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Joost |
| Solution 2 | Dirk-Willem van Gulik |
| Solution 3 | |
| Solution 4 | mickmackusa |
