4

$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 
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
algro
  • 639
  • 4
  • 8
  • 25

4 Answers4

16
list($number1, $number2) = explode(' ', $pos);

However, make sure the string has the right format before doing this.

Joost
  • 10,333
  • 4
  • 55
  • 61
1

You could use:

$pos = "98.9 100.2";
$vals = preg_split("/[\s]+/", $pos);
list($number1, $number2) = $vals;
Pablo Santa Cruz
  • 176,835
  • 32
  • 241
  • 292
  • The character class is not beneficial. For the same string, the `\s` is more than enough to match a literal space. The `+` (one or more) quantifier is not necessary for the sample string. Ultimately, regex is not necessary for the sample string because the delimiting substring is not variable at all. This answer is missing its education explanation. – mickmackusa Mar 22 '22 at 06:18
1

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 :)

Dirk-Willem van Gulik
  • 7,566
  • 2
  • 35
  • 40
1

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)
}
mickmackusa
  • 43,625
  • 12
  • 83
  • 136