CI 4 Passing Parameters in Views

While working with views, we can pass data into it by controllers. This makes the view dynamic.

There are several ways to pass data from controllers to views. Here we have the following –

  • By passing an array
  • By using PHP function compact

Passing an Array of data

Say from Home.php default controller we want to send data to welcome_message.php view file.

<?php

namespace App\Controllers;

class Home extends BaseController
{
	public function index()
	{
		// Method #1
		$data = [
			"name" => "Sanjay",
			"email" => "onlinewebtutorhub@gmail.com",
			"designation" => "Web Developer"
		];

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

	public function index2()
	{
		// Method #2
		$data["name"] = "Sanjay";
		$data["email"] = "onlinewebtutorhub@gmail.com";
		$data["designation"] = "Web Developer";

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

	public function index3()
	{
		// Method #3
		return view('welcome_message', array(
			"name" => "Sanjay",
			"email" => "onlinewebtutorhub@gmail.com",
			"designation" => "Web Developer"
		));
	}
}

By Using PHP “compact” function

We will use compact function of PHP.

<?php

namespace App\Controllers;

class Home extends BaseController
{
	public function index()
	{
		// Method #1
		$name = "Sanjay";
		$email = "onlinewebtutorhub@gmail.com";
		$designation = "Web Developer";

		return view('welcome_message', compact("name", "email", "designation"));
	}
}

Access values to views

We have passed values from controller to view file. To get value simply we will use key as a variable means name, email, designation you can see they are array keys. When we access we use like $name, $email & $designation.

Open welcome_message.php view file where we passed values.

We can access values like

<?php echo $name;  ?>

<?php echo $email;  ?>

<?php echo $designation;  ?>

Using PHP Shorthand operator

<?= $name ?>

<?= $email ?>

<?= $designation ?>

Sanjay KumarHello friends, I am Sanjay Kumar a Web Developer by profession. Additionally I'm also a Blogger, Youtuber by Passion. I founded Online Web Tutor and Skillshike platforms. By using these platforms I am sharing the valuable knowledge of Programming, Tips and Tricks, Programming Standards and more what I have with you all. Read more