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.
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
.
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.
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.
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!