942

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
6
  • 99
    Reader beware: there is no real answer to this question :( Jul 8, 2013 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. May 26, 2016 at 18:40
  • 18
    With all the chains of uncertainty and 'usually'.
    – kettlecrab
    Feb 6, 2017 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). Apr 30, 2018 at 6: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. Sep 20, 2018 at 16:19

36 Answers 36

1444
Answer recommended by PHP Collective

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;
15
  • 10
    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, 2011 at 4:25
  • 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. Jan 30, 2013 at 20:39
  • 36
    Depending on the context, it might not be safe to assume that . is the decimal point separator. en.wikipedia.org/wiki/… Feb 23, 2014 at 3: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. Aug 4, 2016 at 4: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, 2019 at 14:49
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().

9
  • 16
    Note that (double) is just an alias for (float).
    – deceze
    Dec 16, 2011 at 4: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, 2011 at 12:35
  • 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, 2015 at 14:17
  • 7
    intval is useful because then you can use it in array_map('intval', $arrayOfStrings); which you can't do with casting.
    – icc97
    Nov 23, 2016 at 20:10
  • 4
    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, 2017 at 8:43
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
?>
5
  • 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. Aug 26, 2016 at 19:38
  • 1
    any idea if I want to convert "12.7896" in to 12.7896? Nov 28, 2019 at 15:20
  • use floatval() to convert a string to a float. floatval("12.7896") will return 12.7896
    – gopeca
    Nov 29, 2019 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. Feb 6, 2020 at 9:00
  • You do not necessarilly know if the value is float or int, this will arbitrarilly kill all decimals, not what the OP asked for Apr 10 at 9:51
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.

10
  • 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 3, 2013 at 18:19
  • 5
    honzasp is right, for example in JavaScript typeof('123'+0) gives 'string', because '123'+0 gives '1230'.
    – Oriol
    Feb 24, 2013 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, 2013 at 4:16
  • 14
    @oriol in javascript you need to add the number to zero 0+'123' to get 123 Jun 22, 2013 at 14:25
  • 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, 2015 at 14:15
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;
3
  • this worked for me to convert to json only numeric fields to numbers
    – Polymath
    Aug 24, 2022 at 10:34
  • Perfect solution that allows to convert from string to integer and float in one line without checking if it contains the separator. Great, thanks Nov 10, 2022 at 14:25
  • This is the right solution, works in all cases. Jan 5 at 7:47
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;
5
  • Warning: hack detected.
    – Greg
    Aug 21, 2019 at 8: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. Aug 22, 2019 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.) Oct 9, 2019 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 9, 2019 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.) Aug 13, 2020 at 22:20
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.

9
  • 3
    Possibly less dirty? strpos($val, '.') === false ? intval($val) : floatval($val);
    – jchook
    Apr 21, 2016 at 15:43
  • 4
    @jchook Possibly dirtier because it's locale-dependent - eg '0,4' instead of '0.4'.
    – Nick Rice
    Apr 28, 2017 at 13:16
  • 4
    @jchook that breaks on cases like 2.1e2, it has decimal point, but resulting number is integer Sep 18, 2019 at 12:01
  • 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, 2019 at 0:28
  • 4
    Just use the + identity operator: var_dump(+'0.4', +'4'), gives you a float and an int. php.net/manual/en/language.operators.arithmetic.php
    – tvanc
    Nov 6, 2019 at 20:57
25

You can use:

(int)(your value);

Or you can use:

intval(string)
6
  • what if the entered number is '2.3456' how I get 2.3456?
    – Sara
    Dec 16, 2011 at 4:30
  • 10
    the question is also about floats.
    – taseenb
    Sep 7, 2013 at 16:59
  • Show me 1 linefrom OP where it says float? before pass comments and down votes look at Original Post.
    – noobie-php
    Sep 7, 2013 at 19:15
  • 4
    The example shows floats, it is asking how to convert numeric strings into numeric values (floats and integers)
    – taseenb
    Sep 8, 2013 at 1:18
  • 1
    @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? Oct 9, 2019 at 18:02
22

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

2
  • 6
    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.
    – Sara
    Dec 16, 2011 at 4:15
  • NOT WORKED FOR ME IT CONVERTED "3" TO 0 ZERO.
    – Kamlesh
    Mar 27, 2022 at 14:08
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)
1
  • I got this error A non well formed numeric value encountered. any idea? Nov 28, 2019 at 15:21
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
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.
    – Daryl
    Jun 11, 2021 at 21:17
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

2
  • 3
    get_numeric(010); // int 8 get_numeric('010'); // int 10
    – vralle
    Apr 6, 2022 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, 2022 at 21:30
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

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

3
  • 1
    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-conversion
    – th3pirat3
    Jul 4, 2020 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.) Aug 13, 2020 at 23:00
  • Indeed, var_dump((int) '123Z' === 123) // bool(true).
    – Artfaith
    Apr 5 at 11:23
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
5
  • What are the browsers supported with this?
    – MJ DLS
    Nov 14, 2021 at 15:32
  • This is done server side
    – MikelG
    Nov 15, 2021 at 18:19
  • Oh ok, but may I ask can you use this code in all browsers or some browsers?
    – MJ DLS
    Nov 16, 2021 at 23:29
  • Umm... as I've said, this code is for server-side. And the question is for PHP, which is server-side execution.
    – MikelG
    Nov 18, 2021 at 13:59
  • when try echo "3.80" / 1; #output 3.8
    – borma425
    Dec 6, 2022 at 0:00
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)
5
  • After thinking about this a little, I can also suggest division by 1 :)
    – Boykodev
    Oct 3, 2016 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 5, 2016 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 2, 2018 at 9: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? Nov 28, 2019 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. Aug 13, 2020 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;
}
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 2, 2019 at 17:03
  • 1
    for example stackoverflow.com/a/39832873/5411817 suggested the same trick, 3 years prior. Jun 18, 2020 at 6: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. Jun 18, 2020 at 6: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';
5
$a = "10";

$b = (int)$a;

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

2
  • 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.
    – Sara
    Dec 16, 2011 at 4:32
  • 1
    You can always use double or float.
    – Pritom
    Dec 16, 2011 at 4: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.

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. Aug 13, 2020 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
1
  • CAREFUL: This lacks handling of inputs like '.123', '123.', '1.23e6' and possibly others ('0x16', ...).
    – Zrin
    Mar 25, 2022 at 8:20
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)
3
  • JSON is not PHP
    – TV-C-1-5
    Mar 15, 2022 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, 2022 at 22:42
  • I needed to check if POSTed value was an integer and it works perfect for that.
    – lisandro
    Mar 24, 2023 at 12:14
4
function convert_to_number($number) {
    return is_numeric($number) ? ($number + 0) : FALSE;
}
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;
3

Simply you can write like this:

<?php
    $data = ["1","2","3","4","5"];
    echo json_encode($data, JSON_NUMERIC_CHECK);
?>
3
  • 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. Aug 28, 2018 at 11:43
  • 1
    Are you sure about this? This won't convert a string to a number, but an array to a JSON string
    – Nico Haase
    Dec 29, 2018 at 12:00
  • Yes, @NicoHaase if the number is in string format in an array it will convert into a number. Jan 3, 2019 at 8:36
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)

1
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

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;
}
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). Aug 13, 2020 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. Sep 8, 2020 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? Sep 8, 2020 at 20:10
  • 1
    It returns the full number Sep 9, 2020 at 9:18
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.

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";
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.