Home Codeigniter How to pass data from controller to view in CodeIgniter 4?

How to pass data from controller to view in CodeIgniter 4?

Author

Date

Category

To pass data from a controller to a view in CodeIgniter 4, follow these steps:

  1. Create a new controller or open an existing one.
  2. Create an array of data that you want to pass to the view, for example:
$data = [
    'title' => 'Welcome to CodeIgniter 4!',
    'message' => 'This is a demo of passing data from controller to view.'
];
PHP


3. Load the view and pass the data to it using the view() method:

return view('welcome_message', $data);
PHP


In this example, we’re loading a view named “welcome_message” and passing the $data array to it. In the view, we can access the data using the array keys, for example:

<h1><?php echo $title; ?></h1>
<p><?php echo $message; ?></p>
PHP

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Subhash Shipu

PHP Expert

Hey there! I'm a PHP geek on a mission to blog my way through the coding chaos. When I'm not chasing semicolons, I'm busy cuddling my pet Coco, who thinks debugging means chasing her own tail. Join the fun!

Subscribe

Recent posts