The foreach loop iterates over array variables, with optional key access using $key => $value syntax.
<{ foreach( $array as $value ) }>
Content using <{ $value }>
<{ endforeach }>
<{ foreach( $array as $key => $value ) }>
Content using <{ $key }> and <{ $value }>
<{ endforeach }>
<ul>
<{ foreach( $users as $user ) }>
<li><{ $user }></li>
<{ endforeach }>
</ul>
<dl>
<{ foreach( $settings as $key => $value ) }>
<dt><{ $key }></dt>
<dd><{ $value }></dd>
<{ endforeach }>
</dl>
<table>
<{ foreach( $users as $id => $name ) }>
<tr>
<td><{ $id }></td>
<td><{ $name }></td>
</tr>
<{ endforeach }>
</table>
For sequential arrays, the key is the numeric index:
<ol start="0">
<{ foreach( $items as $index => $item ) }>
<li value="<{ $index }>"><{ $item }></li>
<{ endforeach }>
</ol>
<{ foreach( $roles as $user => $role ) }>
<{ if( $role === "admin" ) }>
<strong><{ $user }></strong> (Admin)
<{ else }>
<{ $user }> (<{ $role }>)
<{ endif }>
<{ endforeach }>
<{ foreach( $departments as $dept => $members ) }>
<h3><{ $dept }></h3>
<ul>
<{ foreach( $members as $member ) }>
<li><{ $member }></li>
<{ endforeach }>
</ul>
<{ endforeach }>
<{ foreach( $config as $key => $value ) }>
<{ $key }>=<{ $value }>
<{ endforeach }>
<div
<{ foreach( $attributes as $attr => $val ) }>
<{ $attr }>="<{ $val }>"
<{ endforeach }>
>
Content
</div>
use Myerscode\Templex\Templex;
$templex = new Templex(__DIR__ . '/templates/');
$data = [
'users' => ['admin' => 'Fred', 'mod' => 'Chris', 'user' => 'Tor'],
'settings' => ['theme' => 'dark', 'lang' => 'en'],
'items' => ['apple', 'banana', 'cherry'],
];
$result = $templex->render('my-template.stub', $data);
echo $result;Both foreach and for loops expose metadata variables inside the loop body:
| Variable | Description |
|---|---|
$loop_index |
Zero-based iteration index (0, 1, 2, ...) |
$loop_count |
Total number of iterations |
$loop_first |
true on the first iteration |
$loop_last |
true on the last iteration |
<{ foreach( $tags as $tag ) }>
<{ $tag }><{ if( $loop_last ) }><{ else }>, <{ endif }>
<{ endforeach }>
<ul>
<{ foreach( $items as $item ) }>
<li<{ if( $loop_first ) }> class="first"<{ endif }><{ if( $loop_last ) }> class="last"<{ endif }>><{ $item }></li>
<{ endforeach }>
</ul>
<{ foreach( $steps as $step ) }>
Step <{ $loop_index }> of <{ $loop_count }>: <{ $step }>
<{ endforeach }>
- When no key is specified (
$array as $value), only the value is available in the loop body - When a key is specified (
$array as $key => $value), both key and value are available - Loop variables are scoped to the loop body and override any parent variables with the same name
- Nested foreach loops each have their own scope
- Both sequential and associative arrays are supported