Home  >  Article  >  Backend Development  >  php check if variable exists

php check if variable exists

王林
王林Original
2019-09-27 17:51:426997browse

php check if variable exists

PHP Determines whether constants, variables and functions exist

Determines whether variables are defined: defined()

1 if (defined('CONST_NAME')) {
2     //do something 
3 }

Determine whether the variable exists: isset(). Note that the variable is not declared or is assigned a value of NULL when declared. isset returns FALSE, such as:

1 if (isset($var_name)) {
2     //do something
3 }

Function detection Use function_exists, note that the function name to be detected also needs to use quotation marks, such as:

1 if (function_exists('fun_name')) {
2  fun_name();
3 }

Example:

<?php 
/* 判断常量是否存在*/ if (defined(&#39;MYCONSTANT&#39;)) { 
echo MYCONSTANT; 
} 
//判断变量是否存在 if (isset($myvar)) { 
echo "存在变量$myvar."; 
} 
//判断函数是否存在 if (function_exists(&#39;imap_open&#39;)) { 
echo "存在函数imag_openn"; 
} else { 
echo "函数imag_open不存在n"; 
} 
?>

function_exists determines whether the function exists

1 <?php
2 if (function_exists(&#39;test_func&#39;)) {
3     echo "函数test_func存在";
4 } else {
5     echo "函数test_func不存在";
6 }
7 ?>

filter_has_var function

filter_has_var() function checks whether a variable of the specified input type exists.

If successful, return true, otherwise return false.

1 <?php 
2 if(!filter_has_var(INPUT_GET, "name")) 
3  { 
4  echo("Input type does not exist"); 
5  } 
6 else 
7  { 
8  echo("Input type exists"); 
9  }
10 ?>

Recommended tutorial: PHP video tutorial

The above is the detailed content of php check if variable exists. 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