php string to integer
Cast string to integer in PHP
I’ve been trying to convert string to int in PHP to operate on it, but PHP keeps interpreting it as 0.
I have tried several ways like
But they all give me 0 instead of 89.
How should this be done?
6 Answers 6
The easiest way to convert a string to a number:-
If you are still getting a zero there might be some odd, invisible chars in front of the number. To test for that :-
You can convert string to integer in two ways:
The code below removes the non numeric characters::
or remove double brackets too (for safe)
EDITED
will be good to remove all non numeric values:
and then convert to integer.
I had the same mistake. Indeed when i did var_dump($myvar). it returns string(2) «89» and when i did all the casts fonctions it returned me 0. I search and finally the answer is in this page. So I share with you what i learned. You have just to do a regex php : $myvar = preg_replace(«/[^0-9,.]»,»»,$myvar). It removes all the not number in your string (in my case the string(2)).
Why does PHP convert String to Integer?
I would like to know on what condition PHP decides when to convert from String to Integer and the other way around
I know I should use ‘===’ to get better results, but I’m curious to know why PHP decides to convert the string to integer and not the other way around.
4 Answers 4
From the PHP Manual:
If the string does not contain any of the characters ‘.’, ‘e’, or ‘E’ and the numeric value fits into integer type limits (as defined by PHP_INT_MAX), the string will be evaluated as an integer. In all other cases it will be evaluated as a float.
The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero). Valid numeric data is an optional sign, followed by one or more digits (optionally containing a decimal point), followed by an optional exponent. The exponent is an ‘e’ or ‘E’ followed by one or more digits.
An integer or float is converted to a string representing the number textually (including the exponent part for floats). Floating point numbers can be converted using exponential notation (4.1E+6).
And also (was already given by deceze though) the chapter on Comparison Operators:
If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically.
PHP String-to-Integer Exception
Read a string, SS, and print its integer value; if SS cannot be converted to an integer, print Bad StringBad String.
Note: You must use the String-to-Integer and exception handling constructs built into your submission language. If you attempt to use loops/conditional statements, you will get a 00 score.
11 Answers 11
And here’s another hacky solution using the try <..>catch mechanism:
Only for php 7 (HackersRank uses it):
In general, no. PHP is weakly typed, so you can change integers to strings and vice-versa without any special work. (emphasis mine)
PHP is a dynamic, loosely typed language, that uses copy-on-write and reference counting.
To clarify what exactly is meant by the statement above: PHP is a high level language, weak typing is implicit of the engines preference to convert, or coerce variables into the required type at execution type.
The only exception here is in PHP 7.0 introduced strict type hints. So trying to use them interchangeably with strict type hints on will throw an error
Fatal error: Uncaught TypeError: Argument 1 passed to foo() must be of the type string, integer given, called in /in/Be68h on line 8 and defined in /in/Be68h:5
Php string to integer
Casting objects to arrays is a pain. Example:
$test = new MyClass ();
echo ‘
/*
Array
(
[MyClasspriv] => priv_value
[*prot] => prot_value
[pub] => pub_value
[MyClasspriv] => second_pub_value
)
*/
?>
Yes, that looks like an array with two keys with the same name and it looks like the protected field was prepended with an asterisk. But that’s not true:
/*
MyClasspriv (13) => priv_value
0 77 121 67 108 97 115 115 0 112 114 105 118
*prot (7) => prot_value
0 42 0 112 114 111 116
pub (3) => pub_value
112 117 98
MyClasspriv (11) => second_pub_value
77 121 67 108 97 115 115 112 114 105 118
*/
?>
The char codes show that the protected keys are prepended with ‘\0*\0’ and private keys are prepended with ‘\0’.__CLASS__.’\0′ so be careful when playing around with this.
The object casting methods presented here do not take into account the class hierarchy of the class you’re trying to cast your object into.
Value of uninitialized variable of different data types.
settype($a,’bool’);
var_dump($a); //boolean false
settype($b,’string’);
var_dump($b); //string » (length=0)
settype($c,’array’);
var_dump($c); //array (size=0) empty
settype($d,’int’);
var_dump($d); //int 0
settype($e,’float’);
var_dump($e); //float 0
You REALLY must be aware what you are doing, when you cast a lot in your code. For example, you can accidentaly change FALSE to TRUE (probably not in one line, like here):
if(TRUE === (boolean) (array) (int) FALSE) <
kaboom();
>
namaroulis stated «I found it tricky to check if a posted value was an integer»; to test if a variable is a number or a numeric string (such as form input, which is always a string), you must use is_numeric():
in response to bhsmither at gmail.com
It raises a warning because of the bad enquoted variable
It seems (unset) is pretty useless. But for people who like to make their code really compact (and probably unreadable). You can use it to use an variable and unset it on the same line:
?>
With the unset cast:
?>
Hoorah, we lost another line!
Checking for strings to be integers?
How about if a string is a float?
/* When checking for floats, we assume the possibility of no decimals needed. If you MUST require decimals (forcing the user to type 7.0 for example) replace the sequence:
1+(\.8+)?
with
6+\.7+
*/
Как преобразовать в число строку в PHP?
Очень часто нам приходится работать с числовой информацией, которая представлена в виде строк. В результате возникает необходимость в преобразования строки в число. Язык программирования PHP предлагает нам несколько возможностей для этого. Речь идёт о специальных встроенных в PHP функциях, значительно облегчающих программисту задачу преобразования строки в число. Давайте их рассмотрим.
Преобразование строки в число функцией intval()
Представим, что у нас есть строка, включающая в себя один символ — «2». Вот, как будет выглядеть PHP-код преобразования этой строки в число с помощью встроенной функции intval() :
На выходе получим 2, но уже в виде числа, а не строки.
Остаётся добавить, что вышеописанная функция работает в PHP разных версий: 4, 5, 7+.
Преобразование строки в число путём приведения типов
Возможность приведения типов есть во многих языках программирования, и PHP исключением не является. В PHP мы тоже можем поменять тип переменной, применив для этого синтаксис приведения типов: (int)$variable, (float)$variable. Посмотрим, как это выглядит в коде:
Результатом будет следующий вывод:
Приведение типов можно успешно использовать и в PHP 5 и в PHP 7+.
Преобразование строки в число с помощью settype()
В принципе, вышеперечисленных способов вполне хватит для выполнения преобразования строки в число в PHP. Если же хотите знать больше, ждём вас на наших курсах!