Home  >  Article  >  Backend Development  >  How to determine if a string is not empty in php

How to determine if a string is not empty in php

藏色散人
藏色散人Original
2020-07-14 09:43:015118browse

php method to determine whether a string is empty: 1. Use the "$_MODULE['variable name']" method. The specific judgment syntax is "if($_MODULE['var']) {}else {}"; 2. Just assign the value first and then use empty judgment.

How to determine if a string is not empty in php

Determine whether the string is empty in PHP:

When developing the Taobao SDK template, in module.xml It is often necessary to configure variables to facilitate users to edit templates. But it is inevitable that users forget to enter parameters when entering parameters. In this case, we have to add a code to the PHP code to determine whether the user has entered parameters. There are two commonly used methods:

Method 1: Using $_MODULE['Variable Name']

if($_MODULE['var']) {
     // 这是表示已经输入了值
}
 
else {
     // 这里表示未输入值
}

This method is very simple and I have always used it.

Method 2: Assign value first, and then use empty to judge.

But sometimes, for the sake of code compactness, it is often necessary to initialize the value of the variable at the front of the module's PHP file. Then determine which user inputs are valid one by one. If an error occurs, the error should be displayed to the user in the module. As follows:

$mod_title = $_MODULE['title'];
$mod_style = $_MODULE['style'];
$mod_href = $_MODULE['href'];
 
// ……

In order to prevent abnormal phenomena in the template, we may need to judge $mod_style. Only when the value of $mod_style is specified, the template can be displayed based on it. At this time, the variable $mod_style is generally judged directly, and our most common error method is:

if($mod_style == "") { //.... }

or:

if($mod_style) { //.... }

In actual applications, it does not work like this As we wish, after I personally tested it, I found that no matter which of the above methods is used, even if I do not enter any value, the condition value after if is always true. Therefore, I usually rewrite it into the following form:

if($_MODULE['style']) { //... }

In this way, the problem can be solved correctly, but entering $mod_style is faster and less error-prone than entering $_MODULE['style'] , so I still hope to use $mod_style to judge, and the result is the following code:

if(!empty($mod_style)) { // .... }

After testing, it is normal!

For more related knowledge, please visit PHP Chinese website!

The above is the detailed content of How to determine if a string is not empty 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