Using the string functions

Funtions to convert strings to numbers

intval($var)
floatval($var)

How to convert a string to an integer

Using type casting

<?php
  $value_1 = (int) '42';               // 42
  $value_2 = (int) '42.7';             // 42
  $value_3 = (int) '42 miles';         // 42
  $value_4 = (int) '2,500 feet';       // 2
  $value_5 = (int) 'miles: 42';        // 0
  $value_6 = (int) 'miles';            // 0
  $value_7 = (int) '10000000000';      // PHP_INT_MAX
  $value_8 = (int) '042';              // 42
  $value_9 = (int) '0x42';             // 0
?>

Using the intval() function

<?php
  $value = intval('42');               // 42 
?>

How to convert a string to an floating-point number

Using type casting

<?php
  $value_1 = (float) '4.2';            // 4.2
  $value_2 = (float) '4.2 gallons';    // 4.2
  $value_3 = (float) 'gallons';        // 0
  $value_4 = (float) '1.5e-3';         // 0.0015
  $value_5 = (float) '1e400';          // INF
?>

Using the floatval() function

<?php
  $value = floatval('4.2');            // 4.2
?>

Back