// assign a variable to the view $user = ['name' => 'John', 'email' => 'john@example.com']; $view->assign('user', $user); // access the variable in the view echo $user['name']; // outputs "John"
// assign multiple variables to the view $user = ['name' => 'John', 'email' => 'john@example.com']; $posts = ['title' => 'My First Post', 'body' => 'Lorem ipsum dolor sit amet.']; $view->assign(['user' => $user, 'posts' => $posts]); // access the variables in the view echo $user['name']; // outputs "John" echo $posts['title']; // outputs "My First Post"In this example, we are assigning multiple variables to our view using an associative array. We can then access these variables in our view using their respective keys. Package Library: The View assign function is commonly used in PHP frameworks such as Laravel, Symfony, and CodeIgniter. It is included in many view library packages, including: - Smarty - Twig - Blade (Laravel) - PHPSimpleTemplate - Plates