Home  >  Article  >  Backend Development  >  Obtain variable type and determine whether it is a variable in php_PHP tutorial

Obtain variable type and determine whether it is a variable in php_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 17:13:33893browse

In PHP, since variables do not need to be defined in advance, many times we are confused about the variable types of PHP. However, PHP provides us with the gettype() function to obtain the variable type. It can determine the types of all variables in PHP.

Detect variable type

gettype($var)
This function returns the type of the variable. For example, "String", "Integer", "Boolean", "Float", etc. This function is generally used to verify that the variable is of the type you expect before inserting it into a strictly typed database field.

Check valid variables

The code is as follows
 代码如下 复制代码

// returns string
$var = "hello";
echo gettype($var);
//returns double
$var = 1000.56;
echo gettype($var);
?>

Copy code


// returns string

$var = "hello";

echo gettype($var);

//returns double

$var = 1000.56;
echo gettype($var); ?>

Warning
 代码如下 复制代码

$a = "test";
$b = "anothertest";

echo isset($a)?'true':'false';

输出结果为:true

Do not use gettype() to test a type, as the string it returns may need to change in future versions. In addition, it runs slower due to the inclusion of string comparisons.

 代码如下 复制代码

// returns true
$var = "yes";
echo isset($var) ? "true" : "false";
// returns false
echo isset($test) ? "true" : "false";
?>

Use is_* functions instead.

isset is used to determine whether a variable exists. If so, it returns true, otherwise it returns false. This variable is very useful to us. We can use it to determine whether variables such as get post exist.

The code is as follows Copy code
$a = "test"; $b = "anothertest"; echo isset($a)?'true':'false'; The output result is: true
Example 2
The code is as follows Copy code
// returns true <🎜> $var = "yes"; <🎜> echo isset($var) ? "true" : "false"; <🎜> // returns false <🎜> echo isset($test) ? "true" : "false"; <🎜> ?> The above are two super simple php functions, isset() and gettype() functions, which are not difficult. Friends who need to know more can refer to them. http://www.bkjia.com/PHPjc/629174.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/629174.htmlTechArticleIn PHP, since variables do not need to be defined in advance, many times we are confused about the variable types of PHP. PHP provides us with the gettype() function to get the variable type, which can determine...
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