Loops and Inserting Array Elements into PHP Code Break
Suppose we are given an array:
<?php
$arr = [1, 2, 3, 4, 5];
?>
Let's output each element of this array in its own paragraph:
<?php
foreach ($arr as $elem) {
echo '<p>' . $elem . '</p>';
}
?>
The code can be rewritten with a break in PHP:
<?php foreach ($arr as $elem) { ?>
<p><?= $elem ?></p>
<?php } ?>
For simplicity, you can use the alternative syntax:
<?php foreach ($arr as $elem): ?>
<p><?= $elem ?></p>
<?php endforeach; ?>
Given an array:
<?php
$arr = ['user1', 'user2', 'user3'];
?>
Using this array and a loop, form the following HTML code:
<div>
<h2>user1</h2>
<p>text</p>
</div>
<div>
<h2>user2</h2>
<p>text</p>
</div>
<div>
<h2>user3</h2>
<p>text</p>
</div>
Given an array:
<?php
$arr = [
[
'name' => 'user1',
'age' => 30,
],
[
'name' => 'user2',
'age' => 31,
],
[
'name' => 'user3',
'age' => 32,
],
];
?>
Using this array and a loop, form the following HTML code:
<div>
<p>name: user1</p>
<p>age: 30</p>
</div>
<div>
<p>name: user2</p>
<p>age: 31</p>
</div>
<div>
<p>name: user3</p>
<p>age: 32</p>
</div>