Home  >  Article  >  PHP Framework  >  How to determine whether an array exists in thinkphp template

How to determine whether an array exists in thinkphp template

PHPz
PHPzOriginal
2023-04-17 10:29:081318browse

In the ThinkPHP framework, it is a very common requirement to determine whether an array exists, such as controlling whether a module is displayed based on a certain variable in a template. This article will introduce several methods to determine whether an array exists.

Method 1: Use the empty function to determine

if(!empty($array['key'])){
    //存在
}else{
    //不存在
}

This method is the most commonly used one. The empty function can determine whether a variable is empty. If it is not empty, it returns false, otherwise it returns true. So, if we want to determine whether a key in the array exists, we only need to use !empty.

Method 2: Use isset function to judge

if(isset($array['key'])){
    //存在
}else{
    //不存在
}

isset function is used to judge whether a variable has been declared. When judging an array, it can also be used to judge whether a key exists. If it exists, return true, otherwise return false.

Method 3: Use array_key_exists function to determine

if(array_key_exists('key',$array)){
    //存在
}else{
    //不存在
}

The array_key_exists function is used to determine whether the specified key exists in the array. If it exists, it returns true, otherwise it returns false. It is more strict than the isset function, returning true only if the specified key exists in the array, otherwise it returns false.

Method 4: Use the in_array function to determine

if(in_array('value',$array)){
    //存在
}else{
    //不存在
}

Among them, value is a value in the array. The in_array function is used to check whether a value exists in the array. If it exists, it returns true, otherwise it returns false. We can use this function to determine whether a certain value exists in the array to indirectly determine whether a certain key exists in the array.

To sum up, the above are four common ways to determine whether an array exists. When using, you can choose one or more of them to use in combination according to the actual situation.

The above is the detailed content of How to determine whether an array exists in thinkphp template. 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