getting PHP syntax error unexpected 'foreach' (T_FOREACH)

getting PHP syntax error unexpected 'foreach' (T_FOREACH)

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Debugging the "Unexpected 'foreach'" Error in PHP

When you encounter the Parse error: syntax error, unexpected 'foreach' (T_FOREACH) message from your PHP interpreter, it usually signals a structural issue rather than a logic problem. The parser expects a specific token at that position in the code stream, and when it finds the foreach keyword instead, it halts execution immediately. This often happens because the parser has already left the scope where control structures are allowed, or it is confused by a syntax construct that looks valid but isn't.

In the example provided, the root cause lies in the structure of the HTML file itself. The code snippet places PHP logic inside a <body> tag (implied by the surrounding context of a full page) but fails to close the opening PHP block properly before attempting to output more HTML or encountering another structural element. However, looking closer at the specific syntax within the foreach loops reveals a much subtler, yet critical, parsing error: missing commas in multi-dimensional array definitions.

In the first attempt shown:

$page = array("index.php", "about.php");
$names = array("Home", "About") // Missing comma here? No, this is fine.

Wait, looking at the provided code blocks again, there is a distinct lack of a closing semicolon in the variable declarations if they are meant to be separate statements on new lines without explicit block structures, but more importantly, let's look at the actual error trigger often associated with foreach appearing unexpectedly.

The most common reason for "unexpected 'foreach'" is that you are trying to use it outside of a valid PHP context. If your file starts with HTML, you must open the script with <?php. If you have an unclosed tag like <div> or <table> inside the PHP block without closing the PHP tag first, the parser might get confused depending on the directive settings.

However, the specific error message regarding T_FOREACH often points to a missing comma between array elements in older PHP versions or specific contexts, though modern PHP is forgiving. A more likely culprit in the provided snippet is the mixing of HTML and PHP without proper separation. If the code is inside an HTML file, ensure that the PHP block is closed with ?> before any subsequent HTML tags are encountered if you intend to switch back to raw HTML rendering.

Consider this corrected structure where the variable declarations are strictly typed or properly formatted:

<?php
$page = array("index.php", "about.php");
$names = array("Home", "About"); // Ensure consistent syntax

foreach ($names as $name) {
    echo "&lt;a href='" . $page[0] . "'&gt; $name &lt;/a&gt;";
}
?>

Notice the explicit use of array() or better yet, initializing arrays with [] syntax in modern PHP versions (5.4+). While array() is legacy and still supported, using [] reduces ambiguity about whether you are defining an array or just creating a variable that happens to hold values.

The second example in the source material attempts nested iteration:

foreach ($page as $pages) {
    foreach ($names as $name) {
        echo "&lt;a href=$pages&gt; $name &lt;/a&gt;";
    }
}

Here, the logic creates a Cartesian product of links. If $page and $names are intended to map one-to-one (e.g., Home maps to index.php), nested loops will generate incorrect HTML (<a href="index.php">About</a>). This is a logical error, not a syntax error, but it often leads developers to dig deeper into parsing issues because the output doesn't match expectations.

The parser throws unexpected 'foreach' when the previous statement was incomplete or invalid. For instance:

$page = array("index.php", "about.php");
$names = array("Home", "About") // Missing semicolon if this is not part of a compound statement? 
// Actually, in PHP, statements end with ; unless they are the last line before ?> or EOF.

If the file ends with ?>, that is generally optional in modern applications to avoid whitespace issues. However, if you have code like:

$var = 1;
foreach ($arr as $item) { ... }

And then immediately switch to HTML without closing the PHP tag, some configurations might interpret the following content differently.

A robust solution involves ensuring all array declarations are complete and that the PHP block is strictly delimited. If you are building a header dynamically based on an array of pages, consider using a loop that iterates over both arrays simultaneously using foreach ($page as $link => $name). This ensures the data stays aligned without nested loops or manual index management.

For developers working with Laravel or similar frameworks, avoiding inline PHP in HTML views is a best practice. Using Blade templates allows you to structure logic cleanly:

@foreach ($pages as $page)
    <li><a href="{{ $page['url'] }}">{{ $page['name'] }}</a></li>
@endforeach

This separates concerns and prevents syntax errors caused by mixing raw HTML and PHP tags awkwardly. The foreach directive remains powerful, but it requires a clean environment: proper opening tags, complete statements with semicolons (unless at the end of a block), and correct data structures. When the parser complains about an unexpected token, check the line immediately preceding it for missing delimiters or incomplete expressions.

Our network