How do I convert a string to a number in PHP? How do I convert a string to a number in PHP? php php

How do I convert a string to a number in PHP?


You don't typically need to do this, since PHP will coerce the type for you in most circumstances. For situations where you do want to explicitly convert the type, cast it:

$num = "3.14";$int = (int)$num;$float = (float)$num;


There are a few ways to do so:

  1. Cast the strings to numeric primitive data types:

    $num = (int) "10";$num = (double) "10.12"; // same as (float) "10.12";
  2. Perform math operations on the strings:

    $num = "10" + 1;$num = floor("10.1");
  3. Use intval() or floatval():

    $num = intval("10");$num = floatval("10.1");
  4. Use settype().


To avoid problems try intval($var). Some examples:

<?phpecho intval(42);                      // 42echo intval(4.2);                     // 4echo intval('42');                    // 42echo intval('+42');                   // 42echo intval('-42');                   // -42echo intval(042);                     // 34 (octal as starts with zero)echo intval('042');                   // 42echo intval(1e10);                    // 1410065408echo intval('1e10');                  // 1echo intval(0x1A);                    // 26 (hex as starts with 0x)echo intval(42000000);                // 42000000echo intval(420000000000000000000);   // 0echo intval('420000000000000000000'); // 2147483647echo intval(42, 8);                   // 42echo intval('42', 8);                 // 34echo intval(array());                 // 0echo intval(array('foo', 'bar'));     // 1?>