How do I convert a string to a number in PHP?
Asked Answered
L

36

943

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
Lickerish answered 16/12, 2011 at 4:8 Comment(6)
Reader beware: there is no real answer to this question :(Doublebreasted
@MatthieuNapoli The answer is that usually Php figures it out for you - one of the perks of a dynamic type system.Thema
With all the chains of uncertainty and 'usually'.Pentecost
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).Doublebreasted
@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.Glasshouse
BTW, in JavaScript, the literal integer 2 is stored internally as a 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".Joettajoette
N
1444

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;
Negus answered 16/12, 2011 at 4:13 Comment(15)
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?Lickerish
@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.Negus
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.Latricialatrina
Depending on the context, it might not be safe to assume that . is the decimal point separator. en.wikipedia.org/wiki/…Herring
@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.Cornwell
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.Unalienable
There's also $num = +"3.14";Independency
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 */}Trussell
@Trussell True, but be aware that (int)'99 bottles' == '99 bottles' is true… You'll need some better form of validation than this approach.Negus
This will actually introduce very small errors since floating point numbers are an approximation and not an exact representation.Iva
Just in case, var_dump((int) '123Z' === 123) // bool(true). See: https://mcmap.net/q/53350/-how-do-i-convert-a-string-to-a-number-in-phpJibe
This is not converting to a number but forcint it to become a certain kind of number. I works correctly only if you know what type of number it in in advance and may generates errorsFafnir
@Fafnir Arguably you should know in advance what kind of number you expect…!Negus
@Negus you should does not mean you always do. And why would you do that when you can just $value = +$value That should at least be mentioned in a complete answer as it's really what the OP asked: "changing strings to numbers". Not changing "3.14" to 3 (as in this example)Fafnir
@Fafnir The answer is that PHP basically does that itself as needed. Where this behaviour is not enough for you, you probably have a more restrictive idea of what kind of number you expect, so cast it explicitly yourself. — I wouldn't really recommend either way per se; you should very strictly verify unknown incoming data, much more than a simple conversion of strings to numbers does. As part of such a process, you will nail down the types you get out of this process, making this question moot.Negus
S
269

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

Sophomore answered 16/12, 2011 at 4:12 Comment(9)
Note that (double) is just an alias for (float).Negus
@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).Sophomore
On a side note intval will return 0 if the range falls out of -2147483648 to 2147483647 in 32 bit systemsAbscind
@ed-ta: pretty sure it would return min/max value instead of 0 if you pass strings to it. I.e. intval("9999999999")==2147483647.Ury
But then there's no way to see the difference bewteen intval("0") and intval("foo")?Longwise
intval is useful because then you can use it in array_map('intval', $arrayOfStrings); which you can't do with casting.Luhe
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.)Greataunt
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;Airliner
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.Ujiji
A
94

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
?>
Avera answered 2/6, 2014 at 13:28 Comment(5)
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.Sampan
any idea if I want to convert "12.7896" in to 12.7896?Antrum
use floatval() to convert a string to a float. floatval("12.7896") will return 12.7896Avera
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.Inverness
You do not necessarilly know if the value is float or int, this will arbitrarilly kill all decimals, not what the OP asked forFafnir
C
50

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.

Curator answered 16/12, 2011 at 4:52 Comment(10)
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 :).Fem
honzasp is right, for example in JavaScript typeof('123'+0) gives 'string', because '123'+0 gives '1230'.Jessicajessie
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.Cupellation
Note that by adding a zero you're not 'casting' in the true sense, you're basically converting.Liddell
@oriol in javascript you need to add the number to zero 0+'123' to get 123Maice
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.Hotblooded
@JonathonWisnoski: even more important if you use < or >, as it has different meanings for numbers and strings (i.e. "10" < "2" but 10 > 2).Ury
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.Song
"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.Palaestra
@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.Optative
C
43

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;
Coffelt answered 3/6, 2015 at 9:35 Comment(3)
this worked for me to convert to json only numeric fields to numbersGrume
Perfect solution that allows to convert from string to integer and float in one line without checking if it contains the separator. Great, thanksAmend
This is the right solution, works in all cases.Lloyd
M
39

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;
Malaco answered 10/5, 2018 at 18:31 Comment(5)
Warning: hack detected.Dacoit
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.Malaco
@Dacoit - 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.)Joettajoette
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.Dacoit
@Dacoit - 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.)Joettajoette
B
29

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.

Brooksbrookshire answered 15/9, 2014 at 4:44 Comment(9)
Possibly less dirty? strpos($val, '.') === false ? intval($val) : floatval($val);Plasmasol
@Plasmasol Possibly dirtier because it's locale-dependent - eg '0,4' instead of '0.4'.Parra
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.Plasmasol
@Plasmasol that breaks on cases like 2.1e2, it has decimal point, but resulting number is integerBarber
@TomášBlatný Interesting point, but I think it still works because is_float(2.1e2) === truePlasmasol
@Plasmasol but 2.1e2 === 210, which is not float.Barber
@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.Plasmasol
@Plasmasol 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 :)Barber
Just use the + identity operator: var_dump(+'0.4', +'4'), gives you a float and an int. php.net/manual/en/language.operators.arithmetic.phpIndependency
S
25

You can use:

(int)(your value);

Or you can use:

intval(string)
Soileau answered 16/12, 2011 at 4:13 Comment(6)
what if the entered number is '2.3456' how I get 2.3456?Lickerish
the question is also about floats.Dearly
Show me 1 linefrom OP where it says float? before pass comments and down votes look at Original Post.Soileau
The example shows floats, it is asking how to convert numeric strings into numeric values (floats and integers)Dearly
First check if the number is a float with is_float, and if that passes then cast to with (float) instead of (int).Rhetoric
@MartinvanDriel - It isn't a number. Its a string. The question is how to get either an int or a float result, as appropriate, from a string. Won't is_float return false for a string?Joettajoette
K
22

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

Kirstinkirstyn answered 16/12, 2011 at 4:11 Comment(2)
no I want a common method. which means if its '5' = > it should convert to 5 and if its '2.345' => it should convert to 2.345.Lickerish
NOT WORKED FOR ME IT CONVERTED "3" TO 0 ZERO.Synclastic
F
22

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)
Footing answered 18/7, 2016 at 8:13 Comment(1)
I got this error A non well formed numeric value encountered. any idea?Antrum
D
15

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
Dearly answered 10/8, 2013 at 17:16 Comment(1)
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.Medic
M
14

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

Mikimikihisa answered 29/9, 2020 at 8:11 Comment(2)
get_numeric(010); // int 8 get_numeric('010'); // int 10Enneastyle
@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.Ponton
C
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;
    }
}
Cyclades answered 1/1, 2016 at 19:51 Comment(0)
P
12

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

Persis answered 15/6, 2019 at 17:52 Comment(3)
This is a very good answer. I worked up a bit and wrote some tests for the same tutes.in/php-caveats-int-float-type-conversionHailee
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.)Joettajoette
Indeed, var_dump((int) '123Z' === 123) // bool(true).Jibe
I
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
Iowa answered 21/10, 2021 at 0:13 Comment(5)
What are the browsers supported with this?Susannahsusanne
This is done server sideIowa
Oh ok, but may I ask can you use this code in all browsers or some browsers?Susannahsusanne
Umm... as I've said, this code is for server-side. And the question is for PHP, which is server-side execution.Iowa
when try echo "3.80" / 1; #output 3.8Obturate
E
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)
Elspet answered 3/10, 2016 at 13:29 Comment(5)
After thinking about this a little, I can also suggest division by 1 :)Footing
That's a point! :) By the way your solution is much better than all the scientific notations above. Thank you.Elspet
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;Alina
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?Antrum
@AgnesPalit - PHP is anglo-centric. Only recognizes . as decimal separator. Try '12.24' * 1. Though personally I prefer + 0. Addition instead of multiplication.Joettajoette
S
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;
}
Syzran answered 2/11, 2019 at 15:44 Comment(3)
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.Tomblin
for example https://mcmap.net/q/53350/-how-do-i-convert-a-string-to-a-number-in-php suggested the same trick, 3 years prior.Luxuriant
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.Luxuriant
A
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';
Aland answered 23/1, 2014 at 20:30 Comment(0)
S
5
$a = "10";

$b = (int)$a;

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

Septivalent answered 16/12, 2011 at 4:13 Comment(2)
if the entered number is '7.2345' I can't use (int) then I have to use (float). What I need is a general solution.Lickerish
You can always use double or float.Septivalent
M
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.

Moderato answered 25/2, 2014 at 14:58 Comment(1)
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.Joettajoette
B
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
Blind answered 10/9, 2020 at 10:46 Comment(1)
CAREFUL: This lacks handling of inputs like '.123', '123.', '1.23e6' and possibly others ('0x16', ...).Verdaverdant
G
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)
Gast answered 21/8, 2021 at 19:49 Comment(3)
JSON is not PHPHarlotry
@Harlotry 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.Gast
I needed to check if POSTed value was an integer and it works perfect for that.Shaughn
U
4
function convert_to_number($number) {
    return is_numeric($number) ? ($number + 0) : FALSE;
}
Ullman answered 11/4, 2022 at 10:53 Comment(0)
R
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;
Ramberg answered 29/9, 2013 at 19:18 Comment(0)
H
3

Simply you can write like this:

<?php
    $data = ["1","2","3","4","5"];
    echo json_encode($data, JSON_NUMERIC_CHECK);
?>
Hyalo answered 28/8, 2018 at 11:20 Comment(3)
While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value.Tortile
Are you sure about this? This won't convert a string to a number, but an array to a JSON stringFrancoisefrancolin
Yes, @NicoHaase if the number is in string format in an array it will convert into a number.Hyalo
T
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)

Tourney answered 28/5, 2019 at 19:4 Comment(1)
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).Joettajoette
C
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

Clew answered 4/9, 2013 at 10:53 Comment(0)
S
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;
}
Sedgewick answered 12/2, 2020 at 17:44 Comment(4)
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).Joettajoette
@Joettajoette 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.Sedgewick
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?Joettajoette
It returns the full numberSedgewick
B
2

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.

Blend answered 25/9, 2020 at 8:45 Comment(0)
I
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";
}
Indult answered 29/4, 2015 at 20:34 Comment(0)
A
1
//Get Only number from string
$string = "123 Hello Zahid";
$res = preg_replace("/[^0-9]/", "", $string);
echo $res."<br>";
//Result 123
Allembracing answered 9/9, 2020 at 18:54 Comment(0)
N
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)

Nailbrush answered 14/10, 2022 at 19:17 Comment(1)
it converts everything in number a letter becomes 0.Shaughn
M
1

Update for PHP 8:

There is a function called intval() that allows you to convert a string to a number. You can read more on https://www.php.net/manual/en/function.intval.php

For example:

intval("376") would output 376

or

intval(376) would output 376

Mckinzie answered 5/3 at 19:33 Comment(0)
K
0

PHP will do it for you within limits

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

   printf("%f\n", $num);
?>
Kalb answered 16/12, 2011 at 4:10 Comment(4)
I don't want to out put it. I want to convert it and save it in a variable.Lickerish
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.Kalb
$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.Lickerish
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).]Joettajoette
I
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.

Illiquid answered 5/12, 2022 at 12:29 Comment(0)
E
-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);
Esme answered 19/1, 2018 at 4:26 Comment(1)
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.Joettajoette

© 2022 - 2024 — McMap. All rights reserved.