Home > Article > Backend Development > Discuss how to get the length of an array in Smarty and the detailed explanation of smarty calling php functions_PHP Tutorial
How to get the length of an array in Smarty
Prerequisite:
Allocate an array array to Smarty, assuming that the delimiters of Smarty are '{' and ' }'.
As seen in many materials, when requiring the length of an array in Smarty, you can use the method call of adding |count after the array. That is, get the length of array through {array|count}. But when I was writing the template today, I found that I could not get the length of the array, but only a returned string Array. That is to say, it only returns the result of {array}, but not the length of its array.
Looking at the smartyplugins folder, I found that there is no method related to count. In other words, count directly calls the method in php.
Later, through information on the Internet, I found that you can add @ in front of count to correctly obtain the length of the array. Further checking the source code of Smarty, we found that when Smarty processes the method name after the attribute adjuster, it will perform special processing on the one preceded by @. So make a judgment: when calling a function defined in php in the attribute adjuster in Smarty, it can be expressed by adding @.
1. When testing the method of array type, it was found that if the @ symbol is not added, an error will occur. For example: if you want to call the count method on an array to find the length of the array, you can call {array|@count} like this, and if you want to call the end method on an array to get the last set of data in the array, you can use { array|@end}.
2. After testing the string-related functions, I found that they can be called normally with or without @.
3. Others have not been carefully tested. It is not encouraged to call complex php functions in smarty, because the original intention of Smarty is to realize the separation of code and templates. Templates should be considered to be used by interface designers. If too much complex logic is added, it will be harmful to them. It's a torture to say the least.