Blog

How to Pass Data from an Array in a Controller to a View in CodeIgniter
Posted on June 25, 2015 in CodeIgniter, MVC, PHP by Matt Jennings

First Way

Controller File

<?php
class Test extends CI_Controller
{
    public function hello()
    {

        $basketball['player_num'] = array(
            'Kobe' => 'Kobe24',
            'Lebron' => 'LBJ23'
        );

        // Pass the "$basketball" array
        // as a second parameter in the "view" method
        $this->load->view('test', $basketball);
    }
}
?>

View File

<?php $this->load->view('partials/header'); ?>

<h1>Associative Array Passed from another Controller to this View</h1>

<?php
// Data echoed from the "$basketball['player_num']" array
// created in the controller above
echo $player_num['Kobe'] . '<br />';
echo $player_num['Lebron'] . '<br />';
?>

<?php $this->load->view('partials/footer'); ?>

Second Way

Controller File

<?php
class Test extends CI_Controller
{
    public function hello()
    {

        $basketball_num = array(
            'Kobe' => 'Kobe24',
            'Lebron' => 'LBJ23'
        );

        // Pass the "$basketball" array
        // as a second parameter in the "view" method
        $this->load->view('test', $basketball_num);
    }
}
?>

View File

<?php $this->load->view('partials/header'); ?>

<h1>Associative Array Passed from another Controller to this View</h1>

<?php
// Data echoed from the "$player_num" array
// created in the controller above
echo $Kobe . '<br />';
echo $Lebron . '<br />';
?>

<?php $this->load->view('partials/footer'); ?>

Leave a Reply