Q:

How to Convert a String to a Number in PHP

0

How to Convert a String to a Number in PHP

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Use Type Casting

As we know PHP does not require or support explicit type definition in variable declaration. However, you can force a variable to be evaluated as a certain type using type casting.

Let's try out the following example to understand how this works:

<?php
$num = "2.75";
 
// Cast to integer
$int = (int)$num;
echo gettype($int); // Outputs: integer
echo $int; // Outputs: 2
 
// Cast to float
$float = (float)$num;
echo gettype($float); // Outputs: double
echo $float; // Outputs: 2.75
?>

You can use (int) or (integer) to cast a variable to integer, use (float), (double) or (real) to cast a variable to float. Similarly, you can use the (string) to cast a variable to string, and so on.

The PHP gettype() function returns "double" in case of a float for historical reasons.

Alternatively, you can also use the intval() function to get the integer value of a variable.

<?php
echo intval(2);       // Outputs: 2
echo intval(2.75);    // Outputs: 2
echo intval('34');    // Outputs: 34
echo intval('+34');   // Outputs: 34
echo intval('-34');   // Outputs: -34
echo intval(034);     // Outputs: 28
echo intval('034');   // Outputs: 34
echo intval(1e10);    // Outputs: 10000000000
echo intval('1e10');  // Outputs: 10000000000
echo intval(0xff);    // Outputs: 255
echo intval('0xff');  // Outputs: 0
?>

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

PHP  and MySQL Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to Get the First Element of an Array in PHP... >>
<< How to Convert a Date from yyyy-mm-dd to dd-mm-yyy...