array_first_value

A Smarty modifier to retrieve the first value from an array

Overview

The array_first_value modifier is used to extract the first value from an array in an efficient manner.
This modifier is particularly useful when working with user fields or other data that can contain multiple values, but you only need to display the first one. It simplifies templates by eliminating the need for complex array handling.

Example Template Code

{$my_array|array_first_value}

Common Use Cases

Many user fields support multiple values but commonly contain only one. This modifier simplifies accessing that single value:

{* Instead of complex array handling *}
{assign var="colors" value={get_user_field_values field='favorite_colors'}}
{if $colors|count > 0}{$colors[0]}{/if}

{* Use the new modifier *}
{get_user_field_values|array_first_value field='favorite_colors'}

Return Values

The modifier returns different values depending on the input:

  • Valid array with values: Returns the first element from the array, preserving its original data type
  • Empty array: Returns null
  • Non-array input: Returns null
  • Invalid input: Returns null and may log a Smarty error

Important Notes

  • This modifier preserves the original data type of the first array element
  • The modifier only works on template actions which return data. i.e. not functions which assign a variable