How to force value to numeric type in php

青灯夜游
Release: 2023-03-14 10:40:01
Original
2719 people have browsed it

Conversion method: 1. Add the target type "(int)" enclosed in parentheses before the variable, the syntax "(int)$val"; 2. Use the intval() function, the syntax "intval( $val)"; 3. Use settype(), the syntax is "settype($val,"integer")".

How to force value to numeric type in php

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

php forces the value Convert to numeric type

#Method 1: Add the target type "(int)" or "(integer)" enclosed in parentheses before the variable to be converted

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

How to force value to numeric type in php

Method 2: Use the specific conversion function intval()

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

intval() function 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.

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

How to force value to numeric type in php

Method 3: Use the settype() function

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

How to force value to numeric type in php

Instructions:

The settype() function is used to set the variable $var to the specified $type type. Syntax:

settype ( $var ,$type )
Copy after login

$type Settable values:

  • "boolean" (or "bool", starting from PHP 4.2.0)

  • "integer" (or "int" since PHP 4.2.0)

  • "float" (only available since PHP 4.2.0, For "double" used in older versions now deprecated)

  • "string"

  • "array"

  • "object"

  • ##"null" (from PHP 4.2.0 onwards)

settype() function will change The type of the variable itself.

Recommended learning: "

PHP Video Tutorial"

The above is the detailed content of How to force value to numeric 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