Home >Backend Development >PHP Problem >How to determine whether a variable is a number in php

How to determine whether a variable is a number in php

青灯夜游
青灯夜游Original
2021-09-18 17:45:5713258browse

php method to determine whether a variable is a number: 1. Use the "gettype($var)" statement. If the return value is "integer" or "double", it is a number; 2. Use "is_numeric($var) )" statement, if the return value is "TRUE" it is a number and a numeric string.

How to determine whether a variable is a number in php

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

php judgment variable is Not a number

Method 1: Use the gettype() function

<?php
header("Content-type:text/html;charset=utf-8");
$num=123.25;
if(gettype($num)=="integer"||gettype($num)=="double"){
	echo "是数字";
}else{
	echo "不是数字";
}
?>

Output result:

是数字

Instructions: The gettype() function is used to get the type of a variable. The return value can be:

  • boolean

  • integer

  • ##double (Since PHP 4, if it is a float, it will return "double" instead of "float")

  • #string

  • array

  • object

  • resource (resource)

    resource is a special variable type that saves a reference to an external resource; it mainly Describes a PHP extension resource. Resources are created and used through specialized functions.


  • NULL

    NULL is also a special data type. It has only one value, NULL, which means a null value (i.e. The variable has no value).


  • unknown type

##Method 2: Use is_numeric() function

Detect whether the variable $var is a number or a numeric string. If $var is, return TRUE, otherwise return FALSE; syntax "

is_numeric($var)

". <pre class="brush:php;toolbar:false">&lt;?php header(&quot;Content-type:text/html;charset=utf-8&quot;); $num=123; if(is_numeric($num)){ echo &quot;是数字&quot;; }else{ echo &quot;不是数字&quot;; } ?&gt;</pre>Output result:

是数字

Recommended learning: "

PHP Video Tutorial

"

The above is the detailed content of How to determine whether a variable is a number 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