WEB TUTORIALS
PRACTICE EXAMPLES
HTML REFERENCES
CSS REFERENCES
PHP REFERENCES
Advertisements

How to Convert a String to a Number in PHP

Topic: JavaScript / jQueryPrev|Next

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: 1 (return 100000 in PHP 7.1+)
  • echo intval(0xff);    // Outputs: 255
  • echo intval('0xff');  // Outputs: 0
  • ?>

Related FAQ

Here are some more FAQ related to this topic:

Advertisements

Your Feedback:

We would love to hear from you, please drop us a line.