Converting Strings to Numbers in PHP

Q

How To Convert Strings to Numbers?

✍: FYIcenter.com

A

In a numeric context, PHP will automatically convert any string to a numeric value. Strings will be converted into two types of numeric values, double floating number and integer, based on the following rules:

  • The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero).
  • If the valid numeric data contains '.', 'e', or 'E', it will be converted to a double floating number. Otherwise, it will be converted to an integer.

Here is a PHP script example of converting some examples:

<?php 
$foo = 1 + "10.5";
echo "\$foo=$foo; type is " . gettype ($foo) . "\n";
$foo = 1 + "-1.3e3";
echo "\$foo=$foo; type is " . gettype ($foo) . "\n";
$foo = 1 + "bob-1.3e3";
echo "\$foo=$foo; type is " . gettype ($foo) . "\n";
$foo = 1 + "bob3";
echo "\$foo=$foo; type is " . gettype ($foo) . "\n";
$foo = 1 + "10 Small Pigs";
echo "\$foo=$foo; type is " . gettype ($foo) . "\n";
$foo = 4 + "10.2 Little Piggies";
echo "\$foo=$foo; type is " . gettype ($foo) . "\n";
$foo = "10.0 pigs " + 1;
echo "\$foo=$foo; type is " . gettype ($foo) . "\n";
$foo = "10.0 pigs " + 1.0;
echo "\$foo=$foo; type is " . gettype ($foo) . "\n";
?>

This script will print:

$foo=11.5; type is double
$foo=-1299; type is double
$foo=1; type is integer
$foo=1; type is integer
$foo=11; type is integer
$foo=14.2; type is double
$foo=11; type is double
$foo=11; type is double

 

Understanding PHP String Literals and Operations

⇒⇒PHP Tutorials

2016-10-13, 208👍, 0💬