916

I want to convert these types of values, '3', '2.34', '0.234343', etc. to a number. In JavaScript we can use Number(), but is there any similar method available in PHP?

Input             Output
'2'               2
'2.34'            2.34
'0.3454545'       0.3454545
YanDatsiuk
  • 1,885
  • 2
  • 18
  • 30
Sara
  • 14,098
  • 13
  • 34
  • 50
  • 97
    Reader beware: there is no real answer to this question :( – Matthieu Napoli Jul 08 '13 at 16:05
  • 1
    @MatthieuNapoli The answer is that usually Php figures it out for you - one of the perks of a dynamic type system. – Kellen Stuart May 26 '16 at 18:40
  • 17
    With all the chains of uncertainty and 'usually'. – person27 Feb 06 '17 at 17:48
  • I think what I meant 5 years ago is that there is not **a single function** that takes the string and returns a proper `int` or `float` (you usually don't want a `float` when an `int` is given). – Matthieu Napoli Apr 30 '18 at 06:48
  • 4
    @MatthieuNapoli I am glad you clarified your point to mean there is more than one way to skin a cat, rather than there is no way to do this. Casting is very important in database operations, for instance. For example on a parameterized PDO query, there will be a struggle sometimes for the parser to realize it is a number and not a string, and then you end up with a 0 in an integer field because you did not cast the string to an int in the parameter step. – stubsthewizard Sep 20 '18 at 16:19
  • BTW, in JavaScript, the literal integer `2` is stored internally as a [Number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number): "A number literal like 37 in JavaScript code is a **floating-point value, not an integer**. There is no separate integer type in common everyday use. (JavaScript now has a BigInt type, but it was not designed to replace Number for everyday uses. 37 is still a Number, not a BigInt.)" So the only reason `Number(your_string)` does what you want in JS, is logic elsewhere that defaults to display `2` as `"2"` rather than `"2.0"`. – ToolmakerSteve Sep 08 '20 at 20:48

35 Answers35

1403

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;
deceze
  • 510,633
  • 85
  • 743
  • 889
  • 8
    here the situation is bit different I want to convert any string(contains only numbers) to a general number. As U may know in javaScript we can use **parseInt()** to convert string=>int or parseFloat() to convert string=>float. but in general javaScript use Number() to convert string => number. I want a similar method in php? – Sara Dec 16 '11 at 04:25
  • 1
    @sara AFAIK there's no built-in function for that, you'd have to create one yourself which, for example, checks if there's a `.` in the string in which case you cast it to `float`. But, again, this is unnecessary in most circumstances, a string will work just fine. – deceze Dec 16 '11 at 04:41
  • 4
    It was useful for me when I had a month number obtained from a full date string, wich I used to pull a value from a moth names array. Auto casting doesn't happen here because string indexes are valid, but not equivalent. – Cazuma Nii Cavalcanti Jan 30 '13 at 20:39
  • 35
    Depending on the context, it might not be safe to assume that `.` is the decimal point separator. http://en.wikipedia.org/wiki/Decimal_mark#Countries_using_Arabic_numerals_with_decimal_comma – Dave Jarvis Feb 23 '14 at 03:21
  • 4
    @Sara: You can also create a function for converting the string to _number_ by first casting it to integer, then to float and then comparing if both values (integer and float) are equal. If they are, you should return the value as integer, if not, then as a float. Hope you get the idea. – Youstay Igo Aug 04 '16 at 04:38
  • 3
    There are times that you need to pass the integer to file system, it is not a good idea to wait for PHP to do the conversion for you. – AaA Jan 27 '19 at 14:49
  • 1
    There's also `$num = +"3.14";` – tvanc Nov 06 '19 at 20:43
  • Casting isnt' always a good way of doing it, if you don't expand on it. For example, if the original string is `99 bottles of beer on the wall`, and you cast it to int, for example, you'll end up with `99`. This could cause problems if you're relying on the casting result to be used later on. If that's the case, you should probably check `if($afterCasting == $beforeCasting) { /* do stuff */ } else { /* do some other stuff */}` – FiddlingAway Dec 17 '20 at 11:56
  • 1
    @FiddlingAway True, but be aware that `(int)'99 bottles' == '99 bottles'` is true… You'll need some better form of validation than this approach. – deceze Dec 17 '20 at 11:59
  • This will actually introduce very small errors since floating point numbers are an approximation and not an exact representation. – Peter Kionga-Kamau Jan 21 '21 at 00:56
255

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().

fardjad
  • 20,031
  • 6
  • 53
  • 68
  • 16
    Note that `(double)` is just an alias for `(float)`. – deceze Dec 16 '11 at 04:15
  • 5
    @downvoter, I don't know what's wrong with my answer. Note that I posted this before OP edited her question, however this covers the edited question as well (`$num = "10" + 1` example). – fardjad Dec 16 '11 at 12:35
  • On a side note intval will return 0 if the range falls out of -2147483648 to 2147483647 in 32 bit systems – ed-ta Jun 25 '15 at 18:24
  • 2
    @ed-ta: pretty sure it would return min/max value instead of 0 if you pass strings to it. I.e. `intval("9999999999")==2147483647`. – riv Jul 29 '15 at 14:17
  • But then there's no way to see the difference bewteen `intval("0")` and `intval("foo")`? – Olle Härstedt Mar 01 '16 at 10:14
  • 6
    `intval` is useful because then you can use it in `array_map('intval', $arrayOfStrings);` which you can't do with casting. – icc97 Nov 23 '16 at 20:10
  • Note that `"10"+1` simply causes php to call `intval` implicitly, rather than you writing it explicitly. So it works fine, but be aware it's because of php's rules about inserting implicit conversion. (I prefer making things explicit, myself -- it communicates to other programmers that I know I'm treating text as a number, and also PHP is famous for having ..."unexpected" corner cases, among all its rules about implicit conversions.) – not-just-yeti Feb 24 '17 at 15:43
  • 3
    instead of `$num = "10" + 1;` it's better to use `$num = "10" * 1;` since that will not change the value (neutral element of multiplication), this is essentially something like `toNumber(..)` since the final type will be determined by what is needed to convert the string "10" -> (int) 10; "10.1" -> (float) 10.1; – Holly Aug 20 '17 at 08:43
  • Regarding option 2 - since PHP 7.1 operators (+ - * / ** % << >> | & ^) expect numbers and throw a "Warning: A non-numeric value encountered" if you give them something like an empty string. So if there's a chance of that happening better use some math function like ceil or just cast. – nzn Aug 01 '21 at 08:59
91

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

<?php
echo intval(42);                      // 42
echo intval(4.2);                     // 4
echo intval('42');                    // 42
echo intval('+42');                   // 42
echo intval('-42');                   // -42
echo intval(042);                     // 34 (octal as starts with zero)
echo intval('042');                   // 42
echo intval(1e10);                    // 1410065408
echo intval('1e10');                  // 1
echo intval(0x1A);                    // 26 (hex as starts with 0x)
echo intval(42000000);                // 42000000
echo intval(420000000000000000000);   // 0
echo intval('420000000000000000000'); // 2147483647
echo intval(42, 8);                   // 42
echo intval('42', 8);                 // 34
echo intval(array());                 // 0
echo intval(array('foo', 'bar'));     // 1
?>
SharpC
  • 6,974
  • 4
  • 45
  • 40
gopeca
  • 1,601
  • 12
  • 12
  • 8
    IMHO, This is the only correct answer because it is the only one that takes the radix of the numeric string into consideration. All of the responses (even those suggesting a user-defined function) that simply use a type cast will fail if the numeric string has one or more leading zeros, and the string is NOT intended as a number with an octal base. – Syntax Junkie Aug 26 '16 at 19:38
  • any idea if I want to convert "12.7896" in to `12.7896`? – Agnes Palit Nov 28 '19 at 15:20
  • use floatval() to convert a string to a float. floatval("12.7896") will return 12.7896 – gopeca Nov 29 '19 at 10:29
  • Why isn't this the accepted answer? As a PHP outsider I already knew that `(int)$my_str` wouldn't work since I was dealing *specifically* with strings liks `01` and `013` that I want to interpret as base 10... So I wanted a way to explicitly provide the base. – Giacomo Alzetta Feb 06 '20 at 09:00
51

In whatever (loosely-typed) language you can always cast a string to a number by adding a zero to it.

However, there is very little sense in this as PHP will do it automatically at the time of using this variable, and it will be cast to a string anyway at the time of output.

Note that you may wish to keep dotted numbers as strings, because after casting to float it may be changed unpredictably, due to float numbers' nature.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
  • 40
    There are many languages where you cannot cast a string to number by adding a zero, it's usually considered to be an error rather than a valid method of casting :). – Jan Špaček Jan 03 '13 at 18:19
  • 5
    honzasp is right, for example in JavaScript `typeof('123'+0)` gives `'string'`, because `'123'+0` gives `'1230'`. – Oriol Feb 24 '13 at 21:01
  • 5
    Note, in PHP is is recommended that most of the time you use === style comparisons. So if you will be comparing your data it can be very important what type it is stored in. – Jonathon Mar 15 '13 at 04:16
  • Note that by adding a zero you're not 'casting' in the true sense, you're basically converting. – CSᵠ Apr 26 '13 at 10:41
  • 14
    @oriol in javascript you need to add the number to zero `0+'123'` to get `123` – Timo Huovinen Jun 22 '13 at 14:25
  • There are definitely use cases for this. For example, a numeric value submitted via a web form will be transmitted as a string, but it might be desirable to store it on disk as an integer. – Bobby Jack May 20 '15 at 13:38
  • 1
    @JonathonWisnoski: even more important if you use < or >, as it has different meanings for numbers and strings (i.e. "10" < "2" but 10 > 2). – riv Jul 29 '15 at 14:15
  • 1
    This is especially useful when you don't know if the string is an integer of float before hand but the difference is relevant. For example, a colour value could be between 0.0 and 1.0 or it could be between 0 and 255. Using `is_float` on a string doesn't work, but using the `+0` trick will produce a float for `'1.0'` and an integer for `'1'`, allowing you to test `is_float` later without changing the value. – DanielM Nov 04 '15 at 09:43
  • "there is very little sense in this as PHP will do it automatically at the time of using this variable". Only if it knows that you want to use it as a number. This is not the case if e.g. you are stuffing it into JSON and sending it off via an API to a javascript app that expects it to be a number. – Charles Wood Oct 01 '21 at 14:16
  • @JanŠpaček Yes, but we can apply a similar concept of casting a string to a number using a math operation. In Python, PHP and JS we can transform a string into a number multiplying the numeric string times 1. Doing it this way in PHP, '1.0' will be casted to a float and '1' to an int. – Rafael Atías Apr 27 '23 at 12:36
41

Instead of having to choose whether to convert the string to int or float, you can simply add a 0 to it, and PHP will automatically convert the result to a numeric type.

// Being sure the string is actually a number
if (is_numeric($string))
    $number = $string + 0;
else // Let the number be 0 if the string is not a number
    $number = 0;
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
webNeat
  • 2,768
  • 1
  • 20
  • 22
38

Yes, there is a similar method in PHP, but it is so little known that you will rarely hear about it. It is an arithmetic operator called "identity", as described here:

Aritmetic Operators

To convert a numeric string to a number, do as follows:

$a = +$a;
aldemarcalazans
  • 1,309
  • 13
  • 16
  • Warning: hack detected. – Greg Aug 21 '19 at 08:15
  • 1
    Hi @Greg. Did you click on the link posted here? This is what the developers said about this operator: Conversion of $a to int or float as appropriate. "Conversion", here, cannot be understood as a number-to-number conversion. Why? Because from an exclusive arithmetic point of view, this operator is absolutely useless! Multiplying any number by "+1" (the equivalent of identity function) has absolutely no effect on it. Therefore, I cannot imagine other utility for this operator than the type conversion suggested here. – aldemarcalazans Aug 22 '19 at 21:40
  • 4
    @Greg - surely this is *less* of a hack, than most of the other answers. Its a built-in operator, that does exactly what was requested. (Though its probably best to first check `is_numeric`, so have a place to put code to handle strings that can't convert correctly.) – ToolmakerSteve Oct 09 '19 at 18:14
  • I understand that it works perfectly to use an arithmetic operator for casting, but it's really easy to miss. I think it's worth a warning. – Greg Oct 09 '19 at 19:09
  • 3
    @Greg - I agree that any time code does something that may be non-obvious to the reader, a comment is worthwhile! (Though it still isn't a *hack*, as its usage is exactly what the documentation says - though I personally would not have known that, so I would be glad to see a comment there.) – ToolmakerSteve Aug 13 '20 at 22:20
30

If you want get a float for $value = '0.4', but int for $value = '4', you can write:

$number = ($value == (int) $value) ? (int) $value : (float) $value;

It is little bit dirty, but it works.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Aleksei Akireikin
  • 1,999
  • 17
  • 22
  • 3
    Possibly less dirty? `strpos($val, '.') === false ? intval($val) : floatval($val);` – jchook Apr 21 '16 at 15:43
  • 4
    @jchook Possibly dirtier because it's locale-dependent - eg '0,4' instead of '0.4'. – Nick Rice Apr 28 '17 at 13:16
  • Good point. I suppose you could use `localeconv()['decimal_point']` instead of `'.'`. One advantage of the `strpos` solution is that it's almost 2x as fast as casting twice. – jchook Apr 28 '17 at 16:32
  • 4
    @jchook that breaks on cases like `2.1e2`, it has decimal point, but resulting number is integer – Tomáš Blatný Sep 18 '19 at 12:01
  • @TomášBlatný Interesting point, but I think it still works because `is_float(2.1e2) === true` – jchook Sep 23 '19 at 01:47
  • @jchook but `2.1e2 === 210`, which is not float. – Tomáš Blatný Sep 23 '19 at 13:58
  • 1
    @TomášBlatný No it doesn't. That evaluates to false in PHP. You may have confused "float" with "number containing a fractional part"... obviously `210.0` is a float, and in PHP `2.1e2` is a float. Try it. Float has to do with the way the number gets stored in RAM and represented as a numeric literal. – jchook Sep 24 '19 at 00:28
  • @jchook Well I based this on OP's question, where he wants integers if the number isn't decimal. Yes, that statement evaluates to false, but that was more like math representation rather than php :) – Tomáš Blatný Sep 25 '19 at 04:25
  • 4
    Just use the `+` identity operator: `var_dump(+'0.4', +'4')`, gives you a float and an int. https://www.php.net/manual/en/language.operators.arithmetic.php – tvanc Nov 06 '19 at 20:57
25

You can use:

(int)(your value);

Or you can use:

intval(string)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
noobie-php
  • 6,817
  • 15
  • 54
  • 101
22

In PHP you can use intval(string) or floatval(string) functions to convert strings to numbers.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Kashif Khan
  • 2,615
  • 14
  • 14
21

You can always add zero to it!

Input             Output
'2' + 0           2 (int)
'2.34' + 0        2.34 (float)
'0.3454545' + 0   0.3454545 (float)
Boykodev
  • 850
  • 1
  • 10
  • 23
14

Just a little note to the answers that can be useful and safer in some cases. You may want to check if the string actually contains a valid numeric value first and only then convert it to a numeric type (for example if you have to manipulate data coming from a db that converts ints to strings). You can use is_numeric() and then floatval():

$a = "whatever"; // any variable

if (is_numeric($a)) 
    var_dump(floatval($a)); // type is float
else 
    var_dump($a); // any type
taseenb
  • 1,378
  • 1
  • 16
  • 31
  • this is the first good answer here. all the above are BS and dangerous since ``` intval("4C775916") => 4``` is going to potentially cause you a nasty bug. – Daryl Jun 11 '21 at 21:17
12

Here is the function that achieves what you are looking for. First we check if the value can be understood as a number, if so we turn it into an int and a float. If the int and float are the same (e.g., 5 == 5.0) then we return the int value. If the int and float are not the same (e.g., 5 != 5.3) then we assume you need the precision of the float and return that value. If the value isn't numeric we throw a warning and return null.

function toNumber($val) {
    if (is_numeric($val)) {
        $int = (int)$val;
        $float = (float)$val;

        $val = ($int == $float) ? $int : $float;
        return $val;
    } else {
        trigger_error("Cannot cast $val to a number", E_USER_WARNING);
        return null;
    }
}
12

If you want the numerical value of a string and you don't want to convert it to float/int because you're not sure, this trick will convert it to the proper type:

function get_numeric($val) {
  if (is_numeric($val)) {
    return $val + 0;
  }
  return 0;
}

Example:
<?php
get_numeric('3'); // int(3)
get_numeric('1.2'); // float(1.2)
get_numeric('3.0'); // float(3)
?>

Source: https://www.php.net/manual/en/function.is-numeric.php#107326

klodoma
  • 4,181
  • 1
  • 31
  • 42
  • 2
    `get_numeric(010); // int 8` `get_numeric('010'); // int 10` – vralle Apr 06 '22 at 18:04
  • @vralle, Octal literal `010` is parsed to integer value of 8 by php interpreter; it's not kind of conversion can be done at run time. – Samantra Dec 17 '22 at 21:30
10

I've been reading through answers and didn't see anybody mention the biggest caveat in PHP's number conversion.

The most upvoted answer suggests doing the following:

$str = "3.14"
$intstr = (int)$str // now it's a number equal to 3

That's brilliant. PHP does direct casting. But what if we did the following?

$str = "3.14is_trash"
$intstr = (int)$str

Does PHP consider such conversions valid?

Apparently yes.

PHP reads the string until it finds first non-numerical character for the required type. Meaning that for integers, numerical characters are [0-9]. As a result, it reads 3, since it's in [0-9] character range, it continues reading. Reads . and stops there since it's not in [0-9] range.

Same would happen if you were to cast to float or double. PHP would read 3, then ., then 1, then 4, and would stop at i since it's not valid float numeric character.

As a result, "million" >= 1000000 evaluates to false, but "1000000million" >= 1000000 evaluates to true.

See also:

https://www.php.net/manual/en/language.operators.comparison.php how conversions are done while comparing

https://www.php.net/manual/en/language.types.string.php#language.types.string.conversion how strings are converted to respective numbers

Dragas
  • 1,140
  • 13
  • 29
  • 1
    This is a very good answer. I worked up a bit and wrote some tests for the same https://tutes.in/php-caveats-int-float-type-conversion/ – th3pirat3 Jul 04 '20 at 13:10
  • 2
    `is_numeric($str)` helps with this. (As shown in two of the earlier answers - so its not quite accurate that "nobody mentioned the biggest caveat" - though I see no one explained the issue in detail.) – ToolmakerSteve Aug 13 '20 at 23:00
9

Alright so I just ran into this issue. My problem is that the numbers/strings in question having varying numbers of digits. Some have no decimals, others have several. So for me, using int, float, double, intval, or floatval all gave me different results depending on the number.

So, simple solution... divide the string by 1 server-side. This forces it to a number and retains all digits while trimming unnecessary 0's. It's not pretty, but it works.

"your number string" / 1

Input       Output
"17"        17
"84.874"    84.874
".00234"    .00234
".123000"   .123
"032"       32
MikelG
  • 459
  • 4
  • 16
8

In addition to Boykodev's answer I suggest this:

Input             Output
'2' * 1           2 (int)
'2.34' * 1        2.34 (float)
'0.3454545' * 1   0.3454545 (float)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
drugan
  • 789
  • 9
  • 10
  • After thinking about this a little, I can also suggest division by 1 :) – Boykodev Oct 03 '16 at 14:51
  • 1
    That's a point! :) By the way your solution is much better than all the **scientific notations** above. Thank you. – drugan Oct 05 '16 at 20:52
  • this solution solved my problem. In my case, `$id_cron = (string)date('YmdHi'); $target_id_cron = $id_cron - 1;` instead of $target_id_cron = (int)$id_cron - 1; – inMILD May 02 '18 at 09:33
  • 1
    I got this error `A non well formed numeric value encountered` when I want to change string to float `$num = '12,24' * 1`. Any suggestion? – Agnes Palit Nov 28 '19 at 15:18
  • @AgnesPalit - `PHP` is anglo-centric. Only recognizes `.` as decimal separator. Try `'12.24' * 1`. Though personally I prefer `+ 0`. Addition instead of multiplication. – ToolmakerSteve Aug 13 '20 at 23:04
7

Only multiply the number by 1 so that the string is converted to type number.

//String value
$string = "5.1"
if(is_numeric($string)){
  $numeric_string = $string*1;
}
rolodef
  • 115
  • 1
  • 3
  • 8
    Fair enough, but this method (and similar tricks) are already listed in the 24 other answers to this question - I don't see the value in posting it again. – DavidW Nov 02 '19 at 17:03
  • 1
    for example https://stackoverflow.com/a/39832873/5411817 suggested the same trick, 3 years prior. – SherylHohman Jun 18 '20 at 06:14
  • 2
    For the SO platform to work correctly, existing Answers should be upvoted, not duplicated. If there is a typo, either add Comment below the post, or suggest. The SO platform operates in a different way than forums do. But that is part of the value of this platform. Each platform has is strengths. You would add value, in this case, by voting. Or you could comment with additional references/links. On the otherhand, if you had an awesome, game changing explanation, that nobody else offered, you could add an new Answer, while also Upvoting and linking to the previous post. – SherylHohman Jun 18 '20 at 06:14
6

Here is a function I wrote to simplify things for myself:

It also returns shorthand versions of boolean, integer, double and real.

function type($mixed, $parseNumeric = false)
{        
    if ($parseNumeric && is_numeric($mixed)) {
        //Set type to relevant numeric format
        $mixed += 0;
    }
    $t = gettype($mixed);
    switch($t) {
        case 'boolean': return 'bool'; //shorthand
        case 'integer': return 'int';  //shorthand
        case 'double': case 'real': return 'float'; //equivalent for all intents and purposes
        default: return $t;
    }
}

Calling type with parseNumeric set to true will convert numeric strings before checking type.

Thus:

type("5", true) will return int

type("3.7", true) will return float

type("500") will return string

Just be careful since this is a kind of false checking method and your actual variable will still be a string. You will need to convert the actual variable to the correct type if needed. I just needed it to check if the database should load an item id or alias, thus not having any unexpected effects since it will be parsed as string at run time anyway.

Edit

If you would like to detect if objects are functions add this case to the switch:

case 'object': return is_callable($mixed)?'function':'object';
Dieter Gribnitz
  • 5,062
  • 2
  • 41
  • 38
5

I've found that in JavaScript a simple way to convert a string to a number is to multiply it by 1. It resolves the concatenation problem, because the "+" symbol has multiple uses in JavaScript, while the "*" symbol is purely for mathematical multiplication.

Based on what I've seen here regarding PHP automatically being willing to interpret a digit-containing string as a number (and the comments about adding, since in PHP the "+" is purely for mathematical addition), this multiply trick works just fine for PHP, also.

I have tested it, and it does work... Although depending on how you acquired the string, you might want to apply the trim() function to it, before multiplying by 1.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • Of course in PHP the multiply trick works exactly the same as the addition trick - with exactly the same caveats - so there isn't any particular reason to ask computer to do a multiplication. Regardless, the cleanest solution is `$var = +$str;` -- the identity operator. – ToolmakerSteve Aug 13 '20 at 23:16
5

Late to the party, but here is another approach:

function cast_to_number($input) {
    if(is_float($input) || is_int($input)) {
        return $input;
    }
    if(!is_string($input)) {
        return false;
    }
    if(preg_match('/^-?\d+$/', $input)) {
        return intval($input);
    }
    if(preg_match('/^-?\d+\.\d+$/', $input)) {
        return floatval($input);
    }
    return false;
}

cast_to_number('123.45');       // (float) 123.45
cast_to_number('-123.45');      // (float) -123.45
cast_to_number('123');          // (int) 123
cast_to_number('-123');         // (int) -123
cast_to_number('foo 123 bar');  // false
Benni
  • 1,023
  • 11
  • 15
  • CAREFUL: This lacks handling of inputs like '.123', '123.', '1.23e6' and possibly others ('0x16', ...). – Zrin Mar 25 '22 at 08:20
5
$a = "10";

$b = (int)$a;

You can use this to convert a string to an int in PHP.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Pritom
  • 1,294
  • 8
  • 19
  • 37
4

Now we are in an era where strict/strong typing has a greater sense of importance in PHP, I use json_decode:

$num = json_decode('123');

var_dump($num); // outputs int(123)

$num = json_decode('123.45');

var_dump($num); // outputs float(123.45)
Andy
  • 4,901
  • 5
  • 35
  • 57
  • JSON is not PHP – TV-C-1-5 Mar 15 '22 at 22:02
  • 3
    @TV-C-1-5 not sure of the point you are making? Of course JSON is not PHP. PHP provides functions to encode and decode JSON. In the same way PHP provides function to encode and decode base64 - that doesn’t mean base64 _is_ PHP. – Andy Mar 15 '22 at 22:42
  • I needed to check if POSTed value was an integer and it works perfect for that. – lisandro Mar 24 '23 at 12:14
4
function convert_to_number($number) {
    return is_numeric($number) ? ($number + 0) : FALSE;
}
Hef
  • 606
  • 6
  • 16
3

You can use:

((int) $var)   ( but in big number it return 2147483647 :-) )

But the best solution is to use:

if (is_numeric($var))
    $var = (isset($var)) ? $var : 0;
else
    $var = 0;

Or

if (is_numeric($var))
    $var = (trim($var) == '') ? 0 : $var;
else
    $var = 0;
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mehdi Ajdari
  • 75
  • 1
  • 5
3

Simply you can write like this:

<?php
    $data = ["1","2","3","4","5"];
    echo json_encode($data, JSON_NUMERIC_CHECK);
?>
3

There is a way:

$value = json_decode(json_encode($value, JSON_NUMERIC_CHECK|JSON_PRESERVE_ZERO_FRACTION|JSON_UNESCAPED_SLASHES), true);

Using is_* won't work, since the variable is a: string.

Using the combination of json_encode() and then json_decode() it's converted to it's "true" form. If it's a true string then it would output wrong.

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

var_dump($num, $int, $float);

Will output: string(2) "Me" int(0) float(0)

Anuga
  • 2,619
  • 1
  • 18
  • 27
  • No doubt true. But absurdly overkill way to solve something that already has simple solutions provided years earlier. (Just be glad you didn't write it earlier - see [very downvoted answer with same approach](https://stackoverflow.com/a/34191394/199364)). – ToolmakerSteve Aug 13 '20 at 22:50
2

You can change the data type as follows

$number = "1.234";

echo gettype ($number) . "\n"; //Returns string

settype($number , "float");

echo gettype ($number) . "\n"; //Returns float

For historical reasons "double" is returned in case of a float.

PHP Documentation

aksu
  • 5,221
  • 5
  • 24
  • 39
2

If you don't know in advance if you have a float or an integer,
and if the string may contain special characters (like space, €, etc),
and if it may contain more than 1 dot or comma,
you may use this function:

// This function strip spaces and other characters from a string and return a number.
// It works for integer and float.
// It expect decimal delimiter to be either a '.' or ','
// Note: everything after an eventual 2nd decimal delimiter will be removed.
function stringToNumber($string) {
    // return 0 if the string contains no number at all or is not a string:
    if (!is_string($string) || !preg_match('/\d/', $string)) {
        return 0;
    } 

    // Replace all ',' with '.':
    $workingString = str_replace(',', '.', $string);

    // Keep only number and '.':
    $workingString = preg_replace("/[^0-9.]+/", "", $workingString);

    // Split the integer part and the decimal part,
    // (and eventually a third part if there are more 
    //     than 1 decimal delimiter in the string):
    $explodedString = explode('.', $workingString, 3);

    if ($explodedString[0] === '') {
        // No number was present before the first decimal delimiter, 
        // so we assume it was meant to be a 0:
        $explodedString[0] = '0';
    } 

    if (sizeof($explodedString) === 1) {
        // No decimal delimiter was present in the string,
        // create a string representing an integer:
        $workingString = $explodedString[0];
    } else {
        // A decimal delimiter was present,
        // create a string representing a float:
        $workingString = $explodedString[0] . '.' .  $explodedString[1];
    }

    // Create a number from this now non-ambiguous string:
    $number = $workingString * 1;

    return $number;
}
user1657853
  • 141
  • 5
  • Personally, I consider this dubious. Taking an arbitrary, garbage, string, and searching for a number in it, is almost certainly undesireable. Much better to do what php does by default, which is convert (most) garbage strings into "0". Reason: its more obvious what happened, if unexpected strings reach your method - you simply get 0 (unless the string starts with a valid number). – ToolmakerSteve Aug 13 '20 at 22:41
  • 1
    @ToolmakerSteve yes it's problematic, but there is at least this use case where I had no choice: I had to display strings contained in a (not to be modified) sheet "as is", with symbols and so on, and at the same time use the number contained in it. – user1657853 Sep 08 '20 at 15:57
  • OK, that makes sense. What will your answer do, if there are multiple numbers scattered throughout the string? Is this approach useful for code that converts a phone number to only the digits? E.g. user enters `(123)456-7890`, and you want to extract `1234567890` from that? Or is the idea that it finds the first number, so would result in `123` in my example? – ToolmakerSteve Sep 08 '20 at 20:10
  • 1
    It returns the full number – user1657853 Sep 09 '20 at 09:18
1

All suggestions lose the numeric type.

This seems to me a best practice:

function str2num($s){
// Returns a num or FALSE
    $return_value =  !is_numeric($s) ? false :               (intval($s)==floatval($s)) ? intval($s) :floatval($s);
    print "\nret=$return_value type=".gettype($return_value)."\n";
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
1
//Get Only number from string
$string = "123 Hello Zahid";
$res = preg_replace("/[^0-9]/", "", $string);
echo $res."<br>";
//Result 123
Zahid Gani
  • 169
  • 6
1

One of the many ways it can be achieved is this:

$fileDownloadCount          =  (int) column_data_from_db;
$fileDownloadCount++;

The second line increments the value by 1.

hackernewbie
  • 1,606
  • 20
  • 13
1

Use the unary operator (+). For instance:

$n1 = +'7';
$n2 = '2.34';
$n2 = +$n1;

var_dump($n1): int(7) var_dump($n2): float(2.34)

0

You can just add 0 to your string, and you will convert it to number without losing initial original value. Try for example:

dd('0.3454545' + 0)

PHP will handle conversion for you, or as already suggested add + before your string.

ksenija
  • 11
  • 5
0

PHP will do it for you within limits

<?php
   $str = "3.148";
   $num = $str;

   printf("%f\n", $num);
?>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Adrian Cornish
  • 23,227
  • 13
  • 61
  • 77
  • I don't want to out put it. I want to convert it and save it in a variable. – Sara Dec 16 '11 at 04:17
  • 1
    This automagically converted it to a float. PHP's loose type conversion does it for you. Although it may not do what you expect so the other answers with explicit conversion may work better for you. – Adrian Cornish Dec 16 '11 at 04:20
  • $str can contains '5' or '5.258' using printf("%f\n", $str) '5' will out put as 5.000000 (I want it as 5) for 5.280000 (I want it as 5.28) it contains more decimal points. – Sara Dec 16 '11 at 04:41
  • Re *"This automagically converted it to a float."* Not usefully. `$num = $str;` did not change the value at all, of course. And the printf prints something somewhere - so its still a string. This might be more obvious if you used `sprintf` instead! Nowhere in your answer is there a float value that can be extracted and used elsewhere. [Agreed that *internally* it was a float temporarily - but still is not an answer to the question. If OP wanted to *print* the original string, he could simply have done `printf("%s\n", $str)`.] – ToolmakerSteve Aug 13 '20 at 22:48
-2

I got the question "say you were writing the built in function for casting an integer to a string in PHP, how would you write that function" in a programming interview. Here's a solution.

$nums = ["0","1","2","3","4","5","6","7","8","9"];
$int = 15939; 
$string = ""; 
while ($int) { 
    $string .= $nums[$int % 10]; 
    $int = (int)($int / 10); 
} 
$result = strrev($string);
Brendan
  • 474
  • 4
  • 7
  • Thank you for attempting to contribute to the Q&A. But, sorry, not what is being asked in the question. Your code converts an integer to a string. The question is about converting a string to an integer. The question is also not about how to write code to do something that can already be done using built-in features of the language. – ToolmakerSteve Aug 13 '20 at 22:42