Basic PHP Programming Question:

Download Job Interview Questions and Answers PDF

How To Convert Strings to Numbers in PHP?

PHP Interview Question
PHP Interview Question

Answers:

Answer #1
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.


Answer #2
Here is a PHP script example of converting some examples:

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

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


Download PHP Interview Questions And Answers PDF

Previous QuestionNext Question
How To Convert Numbers to Strings in PHP?How To Get the Number of Characters in a String?