Codeigniter 4 – How to Pass value from controller to view

Passing a value from a Controller can be done in 3 ways:

  1. Using an array variable
  2. Using the Array function
  3. Using the Compact function

Sample 1 – Using an array variable

Controller – App/Controllers/Site.php
Controllers > Site.php

public function index() 
{
    
    $data = array(
        "name" => "Online Tutorial",
        "author" => "Mj Octavio",
        "email" => "support@programm3r.com"
    );
    // $name, $author, $email
    return view("site/index", $data);
    
}

Sample 2 – Using the Array function

Controller – App/Controllers/Site.php
Controllers > Site.php

public function index() 
{

    // $name, $author, $email
    return view("site/index", array(
        "name" => "Online Tutorial",
        "author" => "Mj Octavio",
        "email" => "support@programm3r.com")
    );
    
}

Sample 3 – Using the Compact function

Controller – App/Controllers/Site.php
public function index() 
{

    $name = "Online Tutorial"
    $author = "Mj Octavio"
    $email = "support@programm3r.com"
    
    return view("site/index", compact(
        "name",
        "author",
        "email")
    );
    
}
View – App/Views/site/index.php
<html>

<head>
    <title>
        Site Controller | Index Method
    </title>
</head>

<body>
    <h1>
        Welcome to Index method
    </h1>
    <p>
        User Details
        <br>
        Name: <?php echo $name ?> <br/>
        Author: <?php echo $author ?> <br/>
        Email: <?php echo $email ?> 
    </p>
</body>

</html>