Home > Article > Backend Development > PHP programming basics isset and empty
This article introduces the two most commonly used functions isset and empty in the basics of PHP programming, and gives a few examples for your reference.
In basic PHP programming, the two most commonly used functions are the isset function and the empty function. Examples are as follows: <?php /** * empty函数与isset函数用例 * edit bbs.it-home.org */ $arr[] = ''; $arr[] = 0; $arr[] = NULL; $arr[] = null; $arr[] = '0'; $arr[] = ' '; echo "isset\tempty\n"; echo "-------------------------------\n"; foreach ($arr as $key => $val) { echo isset($val) ? 'true': 'false'; echo "\t"; echo empty($val) ? 'true': 'false'; echo "\n"; } ?> Output result: isset empty ---------------------------------- true true true true false true false true true true true false Sometimes when entering a form, especially when configuring, filling in 0 means that the value is 0, but not filling in a value means that the value may be undefined. In this case, the following function can be used to judge: <?php /** * 判断值是否为空 * * 在php中,0,null,array()和''用empty函数判断时都会返回true, 但实际上很多情况下0是不应当被认为是空 * 的。比如在设置参数值时,0可能表示值真的是0,而空字符串则可能表示该值未设置 * * @site bbs.it-home.org * @param mixed $value 变量值 * @param boolean $is_trim 是否要去掉前后空格 * @return boolean */ function isEmpty($value, $is_trim = false) { return $value === null || $value === array() || $value === '' || ($is_trim && is_scalar($value) && trim($value) === ''); } echo isEmpty(0) ? '1':'0'; echo isEmpty('0') ? '1':'0'; ?> Output result: 00 You can see that entering 0 is no longer considered empty, regardless of whether it is a character or a number. How about it? With the above two examples, do you have a deeper love for the PHP function isset and empty function? ! |