Skip to content

PHP By Exalogics

A Simple Easy Site to Learn, Understand and create php

Menu
  • Home
  • Welcome to php by Exalogics
    • Introduction to PHP
    • How to Install PHP on Windows
    • PHP Variables
    • PHP Constants
    • PHP Switch Statement
    • PHP Data Types
    • PHP Operators
    • PHP If Else Statements
    • PHP E-Commerce Development
    • Your First PHP Script
    • PHP Error Handling
    • PHP Frameworks Guide
    • PHP MySQL Database Development
    • PHP Security Best Practices
    • PHP CMS Development
    • PHP Hosting Guide
  • PHP API Development
Menu

How to Loop Through an Array in PHP (foreach, for)

Posted on October 20, 2026






How to Loop Through an Array in PHP (foreach, for)


How to Loop Through an Array in PHP (foreach, for)

Looping through an array is one of the most common tasks in PHP development. Whether you’re building a simple script or a large‑scale application, knowing the right loop construct can improve readability, maintainability, and performance. In this article we’ll explore the two primary ways to iterate over arrays in PHP: foreach and for. You’ll get clear syntax explanations, real‑world examples, and best‑practice tips.

Table of Contents

  1. Why Loop Through an Array?
  2. Using foreach
  3. Using for
  4. Performance Considerations
  5. Best Practices
  6. FAQ

Why Loop Through an Array?

Arrays store collections of values—numbers, strings, objects, or even other arrays. Looping lets you:

  • Process each element without writing repetitive code.
  • Transform data (e.g., map, filter, reduce).
  • Generate dynamic HTML or JSON output.
  • Interact with databases, APIs, or files based on array content.

Using foreach

The foreach construct is the most readable and PHP‑idiomatic way to iterate over arrays. It automatically handles the internal pointer and works with both indexed and associative arrays.

Basic Syntax

foreach ($array as $value) {
    // $value contains the current element
}

Accessing Keys and Values

foreach ($array as $key => $value) {
    // $key is the index or associative key
    // $value is the element's value
}

Example: Looping Through an Indexed Array

$fruits = ['Apple', 'Banana', 'Cherry'];

foreach ($fruits as $fruit) {
    echo "I love $fruit<br>";
}

Example: Looping Through an Associative Array

$user = [
    'name'  => 'Jane Doe',
    'email' => 'jane@example.com',
    'role'  => 'admin'
];

foreach ($user as $field => $value) {
    echo "<strong>$field:</strong> $value<br>";
}

Modifying Array Elements Inside foreach

To change the original array values, iterate by reference:

foreach ($numbers as &$num) {
    $num *= 2; // doubles each element in the original array
}

Using for

The for loop gives you explicit control over the index, making it ideal when you need to:

  • Access elements by numeric position.
  • Iterate a specific number of times (e.g., skip elements).
  • Combine looping with other arithmetic operations.

Basic Syntax

for ($i = 0; $i < count($array); $i++) {
    // $array[$i] is the current element
}

Example: Looping Through an Indexed Array

$colors = ['Red', 'Green', 'Blue'];

for ($i = 0; $i < count($colors); $i++) {
    echo "Color #{$i}: {$colors[$i]}<br>";
}

When to Prefer for Over foreach

  • You need the numeric index for calculations (e.g., pagination offsets).
  • You want to loop only a subset of the array (e.g., first 5 items).
  • You’re working with a SplFixedArray or a custom object that implements ArrayAccess but not Traversable.

Performance Considerations

Both loops are fast, but there are subtle differences:

  • foreach internally uses a copy of the array pointer, which can be slightly slower for very large arrays if you also call count() inside the loop.
  • for with count($array) in the condition recalculates the length on each iteration. Cache the count beforehand for optimal speed:
$len = count($items);
for ($i = 0; $i < $len; $i++) {
    // processing...
}

In most real‑world applications, the performance difference is negligible. Choose the construct that makes your code clearer.

Best Practices

  1. Prefer foreach for readability. It conveys intent without manual index handling.
  2. Cache count() when using for. This prevents unnecessary function calls.
  3. Use references only when you really need to modify the original array. Unnecessary references can lead to hard‑to‑track bugs.
  4. Validate array data. Always ensure the variable you’re looping over is actually an array (or implements Traversable) before the loop.
  5. Escape output. When printing array values into HTML, use htmlspecialchars() to avoid XSS.

FAQ

Can I break out of a foreach loop?

Yes, use break; to exit the loop early, or continue; to skip to the next iteration.

Is there a difference between foreach and while (list())?

The while (list()) construct is older and less readable. foreach is recommended for modern PHP code.

What if the array is empty?

Both loops will simply not execute their bodies. You can check with empty($array) if you need to display a fallback message.

How do I loop through a multidimensional array?

Nested loops are the usual approach. Example:

$matrix = [
    [1, 2],
    [3, 4],
    [5, 6]
];

foreach ($matrix as $row) {
    foreach ($row as $cell) {
        echo $cell . ' ';
    }
    echo "<br>";
}

Can I use foreach with objects?

Yes, if the object implements the Traversable interface (e.g., Iterator, Generator).

Conclusion

Looping through arrays is a fundamental skill for any PHP developer. foreach offers clean, expressive syntax for most use‑cases, while for provides fine‑grained control when you need it. By following the best practices outlined above, you’ll write code that is both efficient and easy to maintain.


Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recent Posts

  • Pakistan Tour Zimbabwe 2024 / 2025 / 2026: A Look at the Forthcoming Series
  • How to Sort Arrays in PHP
  • How to Loop Through an Array in PHP (foreach, for)
  • Pakistan Tour Sri Lanka 2026: A Subcontinent Showdown
  • Pakistan Tour New Zealand 2025: Exploring the Kiwi Conditions

Recent Comments

  1. What are Magic Methods in PHP? (__construct, __destruct, __get, etc.) - 93 Travellers Pakistan on What are Magic Methods in PHP? (__construct, __destruct, __get, etc.)
  2. How to Use Traits in PHP - 93 Travellers Pakistan on How to Use Traits in PHP
  3. What is Polymorphism in PHP? - 93 Travellers Pakistan on What is Polymorphism in PHP?
  4. What is Inheritance in PHP? - 93 Travellers Pakistan on What is Inheritance in PHP?
  5. What is Abstraction in PHP? - 93 Travellers Pakistan on What is Abstraction in PHP?

Archives

  • October 2026
  • September 2026
  • August 2026
  • July 2026

Categories

  • PHP Basics
  • Uncategorized
©2026 PHP By Exalogics | Design: Newspaperly WordPress Theme
imunify-bot-check