Passing Arrays to the View in MVC in PHP
You can also pass arrays to the view. Let's, for example, pass an array of users:
<?php
namespace Project\Controllers;
use Core\Controller;
class PageController extends Controller
{
public function act()
{
return $this->render('page/act', [
'header' => 'users list',
'users' => ['user1', 'user2', 'user3'],
]);
}
}
?>
You can access each element of the array:
<h1><?= $header ?></h1>
<ul>
<li><?= $users[0]; ?></li>
<li><?= $users[1]; ?></li>
<li><?= $users[2]; ?></li>
</ul>
Or you can iterate through the array with a loop and form the necessary HTML code:
<h1><?= $header ?></h1>
<ul>
<?php foreach ($users as $user): ?>
<li><?= $user; ?></li>
<?php endforeach; ?>
</ul>
Perform the described manipulations, and then access our action via the address bar. Make sure that the text from the view you created appears in the browser.