Home >Backend Development >PHP Problem >How to determine whether a string is empty in php
3 judgment methods: 1. Use the "==" operator to determine whether the string is a null character. If it is a null character, it will be empty. The syntax is "string ==''"; 2. Use mb_strlen () Get the length of the string and determine whether the string length is equal to 0. If equal, it is empty. The syntax is "mb_strlen (string, character encoding) == 0"; 3. Use empty() to determine whether the string is empty. Syntax "empty(string variable)", if TRUE is returned, it will be empty.
The operating environment of this tutorial: windows7 system, PHP version 8.1, DELL G3 computer
php determines the string Multiple methods for whether it is empty
Method 1: Use the "==" operator to determine whether the string is an empty character
If it is a null character, the string is empty
If it is not a null character, the string is not empty
<?php header("Content-type:text/html;charset=utf-8"); function f($str){ if($str==''){ echo "字符串为空<br>"; }else{ echo "字符串不为空:".$str."<br>"; } } f(''); f('123'); ?>
Method 2: Use the mb_strlen() function to determine whether the string is empty
mb_strlen() function returns the length of the string and can handle Chinese strings length issue.
If the length of the string obtained is equal to 0, the string is empty
If the length of the string obtained is greater than 0, the string Not empty
<?php header("Content-type:text/html;charset=utf-8"); function f($str){ if(mb_strlen($str,"utf-8")==0){ echo "字符串为空<br>"; }else{ echo "字符串不为空:".$str."<br>"; } } f(''); f('1235'); ?>
Method 3: Use the empty() function to determine whether the string is empty
## The #empty() function is used to check whether a variable is empty.empty ( mixed $var )empty() Determines whether a variable is considered empty. When a variable does not exist, or its value is equal to FALSE, then it is considered not to exist. empty() does not generate a warning if the variable does not exist.
<?php header("Content-type:text/html;charset=utf-8"); function f($str){ if(empty($str)){ echo "字符串为空<br>"; }else{ echo "字符串不为空:".$str."<br>"; } } f(''); f('hello'); ?>Recommended learning: "
PHP Video Tutorial"
The above is the detailed content of How to determine whether a string is empty in php. For more information, please follow other related articles on the PHP Chinese website!