Форматирование строки в число на языке PHP
Язык PHP предоставляет множество простых способов конвертаций строк в числа. Одним условием является то, что строка должна состоять исключительно из числовых символов. Если же строка состоит из набора буквенных символов, то возможно лишь получить ее длину (length) или код символа в числовом формате (intchar\int[] chars).
Арифметический оператор «+» и преобразование через «(int)»
Данный оператор может перевести с року в число без использования встроенных функций. Разберем это на строковом значении:
<?php
$int_1 = +»100″; \\ поставив оператор + перед строкой — получаем конвертацию строки в число
$int_2 = «100» + 0; \\ при сложении строка переводится в число. Мы сохранили значение сложив строку с нулем
$int_3 = 0 + «100»; \\ поменяли местом ноль и строку
$int_4 = (int)»100″; \\ явное преобразование с помощью оператора (int)\\ Функция var_dump($var) возвращает тип переменной и в скобках указывает ее значение
echovar_dump($int_1); \\ int(100)
echovar_dump($int_2); \\ int(100)
echovar_dump($int_3); \\ int(100)
echovar_dump($int_4); \\ int(100)
?>
Преобразование с помощью функции intval()
Функция intval(var) получает в качестве параметра любой тип и преобразует его в integer:
<?php
$str = «100»;
$int_from_str = intval($str); \\ Переводим значение в переменной str в число и сохраняем в другую переменную
echovar_dump($int_from_str); \\ int(100)
<?
Функция settype()
Функция settype(var, type) преобразовывает один тип переменной в другой. В первый параметр вставляется переменная или литерал, который нужно преобразовать, второй параметр указывает в какой тип преобразовывать — sring, integer, float, boolean и т. п.
Пример:
<?php
$str = «100»;
$str = settype($str, «integer»); \\ integer является строковым параметром и обрамляется кавычками
echovar_dump($str); \\ int(100)
?>
Что будет, если все эти возможности применить к символьной строке?
Любая операция, проведенная над символьной строкой будет равна нулю. Не важно: ставится ли плюс перед строкой, умножается ли строка на число или происходит явное преобразования с помощью функций или (int).
Результат всегда будет один. И если применить функцию var_dump(), то результат будет int(0), в некоторых случаях и int(NaN) — Not a Number. Данное значение получается в ходе умножения числа на слово или за счет арифметических операций между символьными строками и числами.
Самым универсальным оператором преобразования числа в строку является «+», поставленный перед строкой: +»44″. Данная конструкция всегда переводит строку в число во всех языках семейства Cи.
Преобразовать строку в число (PHP)
В PHP преобразовать строку в число в PHP можно тремя способами. Функцией bool settype (mixed &var, string type) , функцией int intval(mixed var [,int base]) или приведением к типу — (int) или (integer) .
Пример
Например есть строка «123» нужно преобразовать ее в тип integer .
Приведение к типу (int)
settype()
intval()
Быстродействие
В плане быстродействия самым быстрым оказался первый способ (приведение к типу — (int)$str ), номером 2 оказался способ settype() и самым медленным оказался способ intval() .
Скорость измерялась обычным способом, строка «123» 1 миллион раз преобразовывалась в тип int .
Как преобразовать строку в число php
Cast a string to binary using PHP < 5.2.1
$binary = unpack(‘c*’, $string);
I found it tricky to check if a posted value was an integer.
is_int ( $_POST [ ‘a’ ] ); //false
is_int ( intval ( «anything» ) ); //always true
?>
A method I use for checking if a string represents an integer value.
<?php
function check_int ( $str )
<
return is_numeric ( $str ) && intval ( $str ) — $str == 0 ;
>
?>
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:
$hello = ‘Hello world’ ;
print $hello ;
unset( $hello );
$hello = ‘Hello world’ ;
$hello = (unset) print $hello ;
?>
Hoorah, we lost another line!
Correct me if I’m wrong, but that is not a cast, it might be useful sometimes, but the IDE will not reflect what’s really happening:
<?php
class MyObject <
/**
* @param MyObject $object
* @return MyObject
*/
static public function cast ( MyObject $object ) <
return $object ;
>
/** Does nothing */
function f () <>
>
class X extends MyObject <
/** Throws exception */
function f () < throw new exception (); >
>
$x = MyObject :: cast (new X );
$x -> f (); // Your IDE tells ‘f() Does nothing’
?>
However, when you run the script, you will get an exception.
In my much of my coding I have found it necessary to type-cast between objects of different class types.
More specifically, I often want to take information from a database, convert it into the class it was before it was inserted, then have the ability to call its class functions as well.
The following code is much shorter than some of the previous examples and seems to suit my purposes. It also makes use of some regular expression matching rather than string position, replacing, etc. It takes an object ($obj) of any type and casts it to an new type ($class_type). Note that the new class type must exist:
function ClassTypeCast(&$obj,$class_type) <
if(class_exists($class_type,true)) <
$obj = unserialize(preg_replace»/^O:[0-9]+:\»[^\»]+\»:/i»,
«O:».strlen($class_type).»:\»».$class_type.»\»:», serialize($obj)));
>
>
WHERE’S THE BEEF?
Looks like type-casting user-defined objects is a real pain, and ya gotta be nuttin’ less than a brain jus ta cypher-it. But since PHP supports OOP, you can add the capabilities right now. Start with any simple class.
<?php
class Point <
protected $x , $y ;
public function __construct ( $xVal = 0 , $yVal = 0 ) <
$this -> x = $xVal ;
$this -> y = $yVal ;
>
public function getX () < return $this -> x ; >
public function getY () < return $this -> y ; >
>
$p = new Point ( 25 , 35 );
echo $p -> getX (); // 25
echo $p -> getY (); // 35
?>
Ok, now we need extra powers. PHP gives us several options:
A. We can tag on extra properties on-the-fly using everyday PHP syntax.
$p->z = 45; // here, $p is still an object of type [Point] but gains no capability, and it’s on a per-instance basis, blah.
B. We can try type-casting it to a different type to access more functions.
$p = (SuperDuperPoint) $p; // if this is even allowed, I doubt it. But even if PHP lets this slide, the small amount of data Point holds would probably not be enough for the extra functions to work anyway. And we still need the class def + all extra data. We should have just instantiated a [SuperDuperPoint] object to begin with. and just like above, this only works on a per-instance basis.
C. Do it the right way using OOP — and just extend the Point class already.
<?php
class Point3D extends Point <
protected $z ; // add extra properties.
public function __construct ( $xVal = 0 , $yVal = 0 , $zVal = 0 ) <
parent :: __construct ( $xVal , $yVal );
$this -> z = $zVal ;
>
public function getZ () < return $this -> z ; >// add extra functions.
>
$p3d = new Point3D ( 25 , 35 , 45 ); // more data, more functions, more everything.
echo $p3d -> getX (); // 25
echo $p3d -> getY (); // 35
echo $p3d -> getZ (); // 45
?>
Once the new class definition is written, you can make as many Point3D objects as you want. Each of them will have more data and functions already built-in. This is much better than trying to beef-up any «single lesser object» on-the-fly, and it’s way easier to do.
Re: the typecasting between classes post below. fantastic, but slightly flawed. Any class name longer than 9 characters becomes a problem. SO here’s a simple fix:
function typecast($old_object, $new_classname) <
if(class_exists($new_classname)) <
// Example serialized object segment
// O:5:»field»:9:
$old_serialized_prefix .= «:\»».get_class($old_object).»\»:»;
$old_serialized_object = serialize($old_object);
$new_serialized_object = ‘O:’.strlen($new_classname).’:»‘.$new_classname . ‘»:’;
$new_serialized_object .= substr($old_serialized_object,strlen($old_serialized_prefix));
return unserialize($new_serialized_object);
>
else
return false;
>
Thanks for the previous code. Set me in the right direction to solving my typecasting problem. 😉
If you have a boolean, performing increments on it won’t do anything despite it being 1. This is a case where you have to use a cast.
That will print
I have 1 bar.
I now have 1 bar.
I finally have 2 bar.
Checking for strings to be integers?
How about if a string is a float?
/* checks if a string is an integer with possible whitespace before and/or after, and also isolates the integer */
$isInt = preg_match ( ‘/^\s*([0-9]+)\s*$/’ , $myString , $myInt );
echo ‘Is Integer? ‘ , ( $isInt ) ? ‘Yes: ‘ . $myInt [ 1 ] : ‘No’ , «\n» ;
/* checks if a string is an integer with no whitespace before or after */
$isInt = preg_match ( ‘/^[0-9]+$/’ , $myString );
echo ‘Is Integer? ‘ , ( $isInt ) ? ‘Yes’ : ‘No’ , «\n» ;
/* 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:
[0-9]+(\.[0-9]+)?
with
[0-9]+\.[0-9]+
*/
/* checks if a string is a float with possible whitespace before and/or after, and also isolates the number */
$isFloat = preg_match ( ‘/^\s*([0-9]+(\.[0-9]+)?)\s*$/’ , $myString , $myNum );
echo ‘Is Number? ‘ , ( $isFloat ) ? ‘Yes: ‘ . $myNum [ 1 ] : ‘No’ , «\n» ;
/* checks if a string is a float with no whitespace before or after */
$isInt = preg_match ( ‘/^[0-9]+(\.[0-9]+)?$/’ , $myString );
How do I convert a string to a number in PHP?
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?
35 Answers 35
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:
There are a few ways to do so:
Cast the strings to numeric primitive data types:
Perform math operations on the strings:
To avoid problems try intval($var) . Some examples:
![]()
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.
![]()
![]()
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.
![]()
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:
To convert a numeric string to a number, do as follows:
If you want get a float for $value = ‘0.4’ , but int for $value = ‘4’ , you can write:
It is little bit dirty, but it works.
![]()
![]()
![]()
In PHP you can use intval(string) or floatval(string) functions to convert strings to numbers.
![]()
You can always add zero to it!
![]()
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() :
![]()
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.
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:
![]()
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:
That’s brilliant. PHP does direct casting. But what if we did the following?
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 .