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
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.
Other posts you may like...