How can I unset variables from a View's scope in Codeigniter How can I unset variables from a View's scope in Codeigniter codeigniter codeigniter

How can I unset variables from a View's scope in Codeigniter


Using TRUE/FALSE might work better than isset.

Also, the way you are loading the view in the code you posted won't send a variable called $winner to the view unless isWinner() is returning something like array('winner' => 'someval') which may be the case.

TRUE/FALSE might look something like

for($i=0; $i < 100; $i++) {    $test = $this->prizedistributor->isWinner();//isWinner() returns either array('winner' => '') or array('winner' => 'somevalue')    echo $this->load->view("test_view", $winner, TRUE);}   

view

<?php if ($winner):?>    WINNER!<br><?php else: ?>    LOST!<br><?php endif; ?>

example

for($i=0; $i < 100; $i++) {    if($i == 50){        $winner = array('winner' => 123);    }else{        $winner = array('winner' => '');    }    echo $this->load->view("test_view", $winner, TRUE);}     

prints

...LOST!LOST!LOST!LOST!LOST!LOST!WINNER!LOST!LOST!LOST!LOST!LOST!LOST!...

It might help to get a better answer if you include what's going on in isWinner() or at least mention what it's returning.


In Codeigniter 3 you can use method

$this->load->clear_vars();

See it in documentation


OK so you seem to know CI caches variables that are passed to the view. The variable names depend on the keys of the data you pass to $this->load->view().

// $myvar will be cached as "true"$this->load->view('myview', array('myvar' => true));// $myvar will still be there$this->load->view('myview');// $myvar will still be there, because myvar has not changed$this->load->view('myview', false);$this->load->view('myview', array());

To unset $myvar, you have to do it explicitly:

$this->load->view('myview', array('myvar' => null));

Your code:

$test = $this->prizedistributor->isWinner();echo $this->load->view("simulateResponse", $test, TRUE);

If $test is just false or null, it won't unset or change the variables already cached. It does nothing actually. You can use something more like this:

$test = $this->prizedistributor->isWinner();echo $this->load->view("simulateResponse", array('winner' => $test), TRUE);

Have isWinner() return true/false instead of an array.

Unfortunately I think you can't truly unset the variable, but you can set it to null/false.

isset($var) will return false if $var === null.