0

I'm working with CodeIgniter, passing an object to a view within a foreach loop. I've noticed that 'view2' prints the number '2' during the first iteration of the loop, but I can't determine why it also continues to print '2' during the second iteration.

Is this behavior due to the objects sharing memory addresses, or is it an issue with the variables used within the loop?

Controller

function controller() {
    $result = (object) [
        (object) [ "a" => 1, "b" => 2 ],
        (object) [ "a" => 3 ]
    ];

    $this->load->view("view1", $result);
}

view1

<?php 
    foreach($result as $index => $res) {
        if($index == 0) {
            $this->load->view("view2", $res);
        } else {
            $this->load->view("view2");
        }
    }

?>

view2

echo $b
3
  • Probably because $b is already defined in the main view (from which view2 is loaded), so the context / scope is the same. I don't know CodeIgniter particularly but that's my asumption. Commented Mar 26, 2024 at 10:51
  • because in the second object b is not defined, so it is getting value from old instance that is 2. if you modify (object) [ "a" => 3, "b" => 3] , it will print 23 Commented Mar 26, 2024 at 12:32
  • Semi-relevant: Codeigniter : variables scope when calling a view from within a view. Odd Commented Mar 26, 2024 at 21:01

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.