How can I know the size of an array in Blade template?

Stefan Izdrail

Founder & Senior Architect · 2026-06-29

Laravel Company
Title: Understanding Array Sizes in Blade Templates: A Comprehensive Guide for Developers Body:

Knowing the size of an array is a fundamental skill for any developer. The Laravel framework, with its flexible template engine named Blade, allows you to accomplish this task in a clean and concise manner. In this article, we'll walk through how to access an array's length from within your Blade templates while offering practical examples and relevant best practices.

Step 1: Declare the Variable

Firstly, you need to define an array that will contain your data. Let's say we have a collection of movies stored in the variable $movies:

Now, let's use our Blade template to render the information about these movies. For this example, we want to display only the films where the length of their title is greater than 10 characters.

Step 2: Accessing Array Length in an If Statement

We can start by checking whether our array $movies has any elements in it and then iterate through each movie to find the ones with a title length greater than 10. Let's use the PHP function count() to get the size of the $movies array:
 0): ?>
    @foreach ($movies as $movie)
        @if (strlen($movie) > 10)
            {{-- Show movie details --}}
        @endif
    @endforeach
@else
    

No movies found.

@endif
In this example, we're first checking if $movies has any items with count(). If not, a friendly message is displayed. Otherwise, the movies are iterated by looping through them using a foreach statement. Within each movie iteration, we use another conditional statement (strlen($movie) > 10), which checks the length of the current movie title to see if it's greater than 10 characters.

Step 3: Using Ternary Operator for Simplified Code

We can further simplify our code by using the ternary operator inside our Blade template:
 0): ?>
    @foreach ($movies as $movie)
        @if (strlen($movie) > 10)
            {{-- Show movie details --}}
        @else
            {{-- Show no movie details message --}}
        @endif
    @endforeach
@else
    

No movies found.

@endif
This code block also checks the length of each movie title and shows either movie details or a message stating that no movie meets the criteria. However, it is more compact and concise by using the ternary operator to make our code easier to read and maintain.

Summary

In conclusion, we have discussed how to check an array's size in your Blade templates while providing relevant examples and best practices for efficient programming. By following these steps and incorporating the necessary tools and techniques, you can confidently create well-structured code that is both accurate and easy to maintain. To further enhance your understanding of Laravel and Blade, visit https://laravelcompany.com/blog for more resources on advanced development topics.