Конвертация в число php

intval

Returns the int value of value , using the specified base for the conversion (the default is base 10). intval() should not be used on objects, as doing so will emit an E_WARNING level error and return 1.

Parameters

The scalar value being converted to an integer

The base for the conversion

  • if string includes a «0x» (or «0X») prefix, the base is taken as 16 (hex); otherwise,
  • if string starts with «0», the base is taken as 8 (octal); otherwise,
  • the base is taken as 10 (decimal).

Return Values

The integer value of value on success, or 0 on failure. Empty arrays return 0, non-empty arrays return 1.

The maximum value depends on the system. 32 bit systems have a maximum signed integer range of -2147483648 to 2147483647. So for example on such a system, intval(‘1000000000000’) will return 2147483647. The maximum signed integer value for 64 bit systems is 9223372036854775807.

Strings will most likely return 0 although this depends on the leftmost characters of the string. The common rules of integer casting apply.

Changelog

Version Description
8.0.0 The error level when converting from object was changed from E_NOTICE to E_WARNING .

Examples

Example #1 intval() examples

The following examples are based on a 64 bit system.

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
echo intval ( ‘042’ ); // 42
echo intval ( 1e10 ); // 10000000000
echo intval ( ‘1e10’ ); // 10000000000
echo intval ( 0x1A ); // 26
echo intval ( ‘0x1A’ ); // 0
echo intval ( ‘0x1A’ , 0 ); // 26
echo intval ( 42000000 ); // 42000000
echo intval ( 420000000000000000000 ); // -4275113695319687168
echo intval ( ‘420000000000000000000’ ); // 9223372036854775807
echo intval ( 42 , 8 ); // 42
echo intval ( ’42’ , 8 ); // 34
echo intval (array()); // 0
echo intval (array( ‘foo’ , ‘bar’ )); // 1
echo intval ( false ); // 0
echo intval ( true ); // 1
?>

Notes

Note:

The base parameter has no effect unless the value parameter is a string.

See Also

  • boolval() — Get the boolean value of a variable
  • floatval() — Get float value of a variable
  • strval() — Get string value of a variable
  • settype() — Set the type of a variable
  • is_numeric() — Finds whether a variable is a number or a numeric string
  • Type juggling
  • BCMath Arbitrary Precision Mathematics Functions

User Contributed Notes 17 notes

It seems intval is interpreting valid numeric strings differently between PHP 5.6 and 7.0 on one hand, and PHP 7.1 on the other hand.

echo intval ( ‘1e5’ );
?>

will return 1 on PHP 5.6 and PHP 7.0,
but it will return 100000 on PHP 7.1.

$n = «19.99» ;
print intval ( $n * 100 ); // prints 1998
print intval ( strval ( $n * 100 )); // prints 1999
?>

intval converts doubles to integers by truncating the fractional component of the number.

When dealing with some values, this can give odd results. Consider the following:

This will most likely print out 7, instead of the expected value of 8.

For more information, see the section on floating point numbers in the PHP manual (http://www.php.net/manual/language.types.double.php)

Also note that if you try to convert a string to an integer, the result is often 0.

However, if the leftmost character of a string looks like a valid numeric value, then PHP will keep reading the string until a character that is not valid in a number is encountered.

«101 Dalmations» will convert to 101

«$1,000,000» will convert to 0 (the 1st character is not a valid start for a number

«80,000 leagues . » will convert to 80

«1.4e98 microLenats were generated when. » will convert to 1.4e98

Also note that only decimal base numbers are recognized in strings.

«099» will convert to 99, while «0x99» will convert to 0.

One additional note on the behavior of intval. If you specify the base argument, the var argument should be a string — otherwise the base will not be applied.

print intval (77, 8); // Prints 77
print intval (’77’, 8); // Prints 63

Источник

Преобразовать строку в число (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)
  • Строку в нижний регистр (PHP)
  • Как инвертировать строку (PHP)
  • Как обрезать строку (PHP)
  • Как обрезать строку (JavaScript)
  • Первые N символов строки цифры (PHP)
  • str_repeat (JavaScript)
  • Разделить строку по разделителю (PHP)
  • Первую букву в верхний регистр (JavaScript)
  • Повторение строки (PHP)
  • Определить поискового бота (PHP)
  • str_pad (JavaScript)

Комментарии

Привет от кво мастера Америке

Вход на сайт

Введите данные указанные при регистрации:

Социальные сети

Вы можете быстро войти через социальные сети:

Источник

Конвертация в число php

Cast a string to binary using PHP < 5.2.1

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.

$foo [ ‘ten’ ] = 10 ; // $foo[‘ten’] is an array holding an integer at key «ten»
$str = » $foo [ ‘ten’]» ; // throws T_ENCAPSED_AND_WHITESPACE error
$str = » $foo [ ten ] » ; // works because constants are skipped in quotes
$fst = (string) $foo [ ‘ten’ ]; // works with clear intention
?>

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!

It would be useful to know the precedence (for lack of a better word) for type juggling. This entry currently explains that «if either operand is a float, then both operands are evaluated as floats, and the result will be a float» but could (and I think should) provide a hierarchy that indicates, for instance, «between an int and a boolean, int wins; between a float and an int, float wins; between a string and a float, string wins» and so on (and don’t count on my example accurately capturing the true hierarchy, as I haven’t actually done the tests to figure it out). Thanks!

May be expected, but not stated ..
Casting to the existing (same) type has no effect.
$t = ‘abc’; // string ‘abc’
$u=(array) $t; // array 0 => string ‘abc’ $v=(array) $u; // array 0 => string ‘abc’

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:

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:

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.
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.
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 = «O:».strlen(get_class($old_object));
$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.

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*(8+)\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 ( ‘/^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:
5+(\.1+)?
with
7+\.5+
*/

/* checks if a string is a float with possible whitespace before and/or after, and also isolates the number */
$isFloat = preg_match ( ‘/^\s*(5+(\.1+)?)\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 ( ‘/^7+(\.3+)?$/’ , $myString );

echo ‘Is Number? ‘ , ( $isFloat ) ? ‘Yes’ : ‘No’ , «\n» ;

Источник

Читайте также:  Typescript cast object to any
Оцените статью