Home > Backend Development > PHP Problem > How to force convert string to int type in php

How to force convert string to int type in php

青灯夜游
Release: 2023-03-15 07:12:01
Original
5506 people have browsed it

php method to force a string to int type: 1. Use the intval() function to get the integer value of the variable, the syntax is "intval (string variable)"; 2. Use settype(), Variables can be set to a specified type with the syntax "settype(string variable, "integer")".

How to force convert string to int type in php

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

Method 2: Use intval() Function

intval() function is used to get the integer value of a variable.

<?php
header("Content-type:text/html;charset=utf-8");
$str = &#39;32.14abc&#39;;
$int = intval($str);
echo $int."<br>";
echo &#39;变量 $int 的类型为:&#39; . gettype($int) . &#39;<br>&#39;;
?>
Copy after login

How to force convert string to int type in php

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

Method 3: Use the settype() function

settype ($var,$type)The function can set the variable$varSet to the specified type $type, $type Settable values:

  • "boolean" (or "bool", As of PHP 4.2.0)

  • "integer" (or "int" as of PHP 4.2.0)

  • "float " (Only available after PHP 4.2.0, "double" used in older versions is now deprecated)

  • "string"

  • "array"

  • "object"

  • "null" (from PHP 4.2.0)

Example:

<?php
header("Content-type:text/html;charset=utf-8");
$str = &#39;3542abc&#39;;
settype($str,"integer");
echo $str."<br>";
echo &#39;修改后的类型为:&#39; . gettype($str) . &#39;<br>&#39;;
?>
Copy after login

How to force convert string to int type in php

Description:

The settype() function changes the type of the variable itself.

Recommended learning: "PHP Video Tutorial"

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template