Skip to content

Laravel each() vs foreach() Performance Comparison: Which is Faster?

Master Laravel each() vs foreach() methods with performance benchmarks, code examples, and best practices. Complete Laravel 12 developer guide for optimal collection iteration.

Dasun Kalupahana Updated 2 min read 2.7K views 0 comments
On this page
  1. Introduction
  2. What is Laravel’s each() Method?
  3. What is PHP’s foreach() Method?
  4. Key Differences Between each() and foreach()
  5. Practical Code Examples
  6. Performance Comparison
  7. Benefits of each() Method
  8. Benefits of foreach() Method
  9. When to Use Each Method
  10. Conclusion

Introduction

When working with Laravel, developers often encounter situations where they need to iterate through collections or arrays. Two popular methods for this task are Laravel’s each() method and PHP's native foreach() loop. Understanding when and how to use each method can significantly impact your application's performance and code readability.

What is Laravel’s each() Method?

Laravel’s each() method is a collection method that allows you to iterate over each item in a collection while maintaining the fluent interface. It's part of Laravel's Collection class and provides a more functional programming approach to iteration.

$collection->each(function ($item, $key) {
    // Your logic here
});

What is PHP’s foreach() Method?

The foreach() construct is PHP's native way to iterate through arrays and objects. It's been a core part of PHP since version 4 and provides a straightforward approach to loop through data structures.

foreach ($array as $key => $value) {
    // Your logic here
}

Key Differences Between each() and foreach()

1. Return Values

Laravel each() Method:

$users = collect(['John', 'Jane', 'Bob']);

$result = $users->each(function ($user, $index) {
    echo "User {$index}: {$user}\n";
});

// Returns the original collection
// $result still contains ['John', 'Jane', 'Bob']

PHP foreach() Method:

$users = ['John', 'Jane', 'Bob'];

foreach ($users as $index => $user) {
    echo "User {$index}: {$user}\n";
}

// Returns nothing (void)

2. Method Chaining

Laravel each() Method:

$products = collect([
    ['name' => 'Laptop', 'price' => 1000],
    ['name' => 'Phone', 'price' => 500],
    ['name' => 'Tablet', 'price' => 300]
]);

$expensiveProducts = $products
    ->each(function ($product) {
        Log::info("Processing: " . $product['name']);
    })
    ->filter(function ($product) {
        return $product['price'] > 400;
    })
    ->pluck('name');

// Result: ['Laptop', 'Phone']

PHP foreach() Method:

$products = [
    ['name' => 'Laptop', 'price' => 1000],
    ['name' => 'Phone', 'price' => 500],
    ['name' => 'Tablet', 'price' => 300]
];

$expensiveProducts = [];
foreach ($products as $product) {
    Log::info("Processing: " . $product['name']);
    if ($product['price'] > 400) {
        $expensiveProducts[] = $product['name'];
    }
}

3. Early Termination

Laravel each() Method:

$numbers = collect([1, 2, 3, 4, 5]);

$numbers->each(function ($number) {
    if ($number === 3) {
        return false; // Stops iteration
    }
    echo $number . "\n";
});
// Output: 1, 2

PHP foreach() Method:

$numbers = [1, 2, 3, 4, 5];

foreach ($numbers as $number) {
    if ($number === 3) {
        break; // Stops iteration
    }
    echo $number . "\n";
}
// Output: 1, 2

Practical Code Examples

Example: Processing User Data

Using Laravel each():

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;

class UserController extends Controller
{
    public function processUsers()
    {
        $users = User::all();
        
        $processedUsers = $users->each(function ($user) {
            // Update last login timestamp
            $user->last_processed_at = now();
            $user->save();
            
            // Send notification
            $user->notify(new AccountProcessedNotification());
        });
        
        return response()->json([
            'message' => 'Users processed successfully',
            'count' => $processedUsers->count()
        ]);
    }
}

Using foreach():

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;

class UserController extends Controller
{
    public function processUsers()
    {
        $users = User::all();
        $processedCount = 0;
        
        foreach ($users as $user) {
            // Update last login timestamp
            $user->last_processed_at = now();
            $user->save();
            
            // Send notification
            $user->notify(new AccountProcessedNotification());
            $processedCount++;
        }
        
        return response()->json([
            'message' => 'Users processed successfully',
            'count' => $processedCount
        ]);
    }
}

Performance Comparison

1. Memory Usage

  • each(): Maintains the collection object in memory, which can use more memory for large datasets
  • foreach(): Generally more memory efficient as it works directly with arrays

2. Execution Speed

// Performance test example
$largeDataset = range(1, 100000);
$collection = collect($largeDataset);

// Test foreach performance
$start = microtime(true);
foreach ($largeDataset as $item) {
    $result = $item * 2;
}
$foreachTime = microtime(true) - $start;

// Test each() performance
$start = microtime(true);
$collection->each(function ($item) {
    $result = $item * 2;
});
$eachTime = microtime(true) - $start;

echo "foreach time: " . $foreachTime . "\n";
echo "each() time: " . $eachTime . "\n";

Benefits of each() Method

1. Fluent Interface

$users = User::where('active', true)
    ->get()
    ->each(function ($user) {
        $user->increment('login_count');
    })
    ->filter(function ($user) {
        return $user->login_count > 10;
    })
    ->values();

2. Consistent API

All Laravel collection methods follow the same pattern, making code more predictable and maintainable.

3. Immutability Support

$originalData = collect([1, 2, 3, 4, 5]);
$processedData = $originalData->each(function ($item) {
    // Process without modifying original
    echo $item * 2;
});
// $originalData remains unchanged

Benefits of foreach() Method

1. Performance

Better performance for simple iterations, especially with large datasets.

2. Memory Efficiency

Lower memory footprint when working with plain arrays.

3. Universal Compatibility

Works with any PHP iterable, not just Laravel collections.

4. Simplicity

// Simple and straightforward
foreach ($items as $item) {
    echo $item;
}

When to Use Each Method

Use Laravel each() When:

  • Working with Laravel collections
  • Need method chaining
  • Want to maintain functional programming style
  • Working with Eloquent models
  • Need to preserve the collection for further operations

Use foreach() When:

  • Performance is critical
  • Working with simple arrays
  • Memory usage is a concern
  • Don’t need method chaining
  • Working with large datasets

Conclusion

Both Laravel’s each() method and PHP's foreach() construct have their place in Laravel development. The each() method excels in scenarios requiring method chaining and functional programming patterns, while foreach() offers superior performance for simple iterations and large datasets.

Choose each() when you need the fluent interface and are working with Laravel collections. Opt for foreach() when performance is critical or when working with simple arrays. Understanding these differences will help you write more efficient and maintainable Laravel applications.

If you found this helpful, feel free to share or drop a comment. Happy coding with Laravel! 🧱✨

Free resources for this topic

Code snippets and fixes for this topic

Get one practical tip every week

New tutorials, fixes and free cheat sheets from DEV Talk, straight to your inbox. No spam, unsubscribe in one click.

Free download: Laravel interview questions (PDF)

Have a question about this post?

Ask the community: other developers and the author can answer.

Ask the community

Get notified about new articles

One click, no email needed. Turn it off anytime with the bell at the top.

Get new articles on your iPhone

Add DEV Talk to your Home Screen, open it, then tap the bell.

Rate this post
0.0
Share

Enjoying the content?

If this article helped you, you can support the author with a coffee. It keeps new posts coming.

Buy me a coffee (opens in a new tab)

Comments 0

Be kind. Comments with links are reviewed before they appear.

No comments yet

Be the first to share your thoughts.

Get new articles in your inbox

Practical tutorials and deep dives, about once a week. No spam, unsubscribe anytime.

Privacy policy

Add DEV Talk to your Home Screen

  1. 1 Tap the Share button in Safari's toolbar.
  2. 2 Scroll down and tap Add to Home Screen.
  3. 3 Tap Add. Open it from the Home Screen to read like an app and to turn on notifications with the bell.

We use cookies to improve your experience and analyze traffic. By continuing, you agree to our Privacy Policy.