Skip to content

last

The 'last' filter is designed to retrieve the last element of an array or string.

Functionality

  • Arrays: If the input value is an array, the last filter returns the last element of that array.
  • Strings: If the input value is a string, the last filter returns the last character of that string.

Syntax

    {{ array_variable | last }} 
Arguments

The last filter does not require any arguments.

Code Samples

Example 1: Last Element of an Array

    {% assign colors = "red,green,blue" | split: "," %}

    {{ colors | last }} 

Output:

blue
Example 2: Last Character of a String

    {% assign message = "Hello, world!" %}

    {{ message | last }} 
Output:
!

Outliers and Special Cases

  • Empty Arrays: If the input array is empty, the last filter returns null.
  • Empty Strings: If the input string is empty, the last filter returns null.
  • Non-Array/String Input: If the input is neither an array nor a string, the last filter returns the original input value unchanged.

Key Points

  • The last filter is a simple and convenient way to access the final element of a sequence.
  • It gracefully handles both arrays and strings.
  • It is particularly useful when you need to extract a specific piece of information from the end of your data.