Home  >  Article  >  Backend Development  >  How to convert to int type in php?

How to convert to int type in php?

青灯夜游
青灯夜游Original
2020-09-30 10:13:4110244browse

Conversion method: 1. Add "(int)" before the variable to be converted to force conversion to int type, for example "(int)3.14", the value is 3; 2. Use the intval() function , the syntax is "intval(value)"; 3. Use the settype() function, the syntax is "settype(value,"int")".

How to convert to int type in php?

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

There are three PHP data types A conversion method:

1. Forced type conversion

Type coercion in PHP is very similar to that in C: in the The variable is preceded by the target type enclosed in parentheses.

The allowed casts are:

  • (int),(integer) - Convert to integer type

  • (bool ),(boolean) - Convert to Boolean type

  • (float),(double),(real) - Convert to floating point type

  • (string)                                                                                                                                                                                                                                         through

  • Note that spaces and tabs are allowed within brackets

    Example: PHP converted to int type
  • <?php  
    $num1=3.14;  
    $num2=(int)$num1;  
    var_dump($num1); //输出float(3.14)  
    var_dump($num2); //输出int(3)  
    ?>
  • Output:

    float 3.14
    int 3
2. Use conversion functions

PHP has 3 specific types of conversion functions:


intval(): used to obtain variables Integer value.

Returns the integer value of variable var by using the specified base conversion (default is decimal). intval() cannot be used with object, otherwise an E_NOTICE error will be generated and 1 will be returned.

floatval(): used to obtain the floating point value of a variable.
  • strval(): used to get the string value of a variable.

  • Example: php converted to int type

    <?php  
    $str="123.9abc";  
    $int=intval($str);     //转换后数值:123  
    var_dump($int);  
    ?>

    Output: php converted to int type
  • int 123
  • 3. Use the general type conversion function settype(mixed var,string type)

settype() function is used to set the type of a variable.

Example:

<?php  
$str="123.9sdc";  
$int=settype($str,"int");  
var_dump($int);  //输出bool(true)  
var_dump($str); //输出int(12)  
?>

Output:

boolean true
int 123

Related recommendations:

php training

The above is the detailed content of How to convert to int type in php?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn