Igor Kromin |   Consultant. Coder. Blogger. Tinkerer. Gamer.

I've come across a requirement in some of my Smarty templates to check if a value of a variable appears in an array. The PHP in_array function does this for you and according to the Smarty documentation any PHP function can be used as a variable modifier so this should be very easy to implement.
Variable modifiers can be applied to variables, custom functions or strings. To apply a modifier, specify the value followed by a | (pipe) and the modifier name. A modifier may accept additional parameters that affect its behavior. These parameters follow the modifer name and are separated by a : (colon). Also, all php-functions can be used as modifiers implicitly (more below) and modifiers can be combined. .


So lets say my variable is named $my_fruit and I want to check if the value is in this array: ['apples', 'oranges', 'peaches', 'dragonfruit']. This is what it would look like in Smarty...
 Smarty
{if $my_fruit|in_array:['apples', 'oranges', 'peaches', 'dragonfruit']}
My fruit is in the array
{/if}




The syntax can be a little confusing. The variable is specified first, followed by the pipe character, then the in_array function. A colon is used to specify an input parameter to the in_array function, which happens to be the array of fruit from above.

-i

A quick disclaimer...

Although I put in a great effort into researching all the topics I cover, mistakes can happen. Use of any information from my blog posts should be at own risk and I do not hold any liability towards any information misuse or damages caused by following any of my posts.

All content and opinions expressed on this Blog are my own and do not represent the opinions of my employer (Oracle). Use of any information contained in this blog post/article is subject to this disclaimer.
Hi! You can search my blog here ⤵
NOTE: (2022) This Blog is no longer maintained and I will not be answering any emails or comments.

I am now focusing on Atari Gamer.