5

I want to define an array which I can use in AppController and in the default layout.

How can I do this in CakePHP?

3 Answers 3

26
$this->set('arr', array('one', 'two'));

// Accessible in controller as 
$this->viewVars['arr'];

// Accessible in view/layout as
echo $arr;
Sign up to request clarification or add additional context in comments.

1 Comment

in CakePhp4 replaced with this : $this->viewBuilder()->getVar('arr');
2

If you set any variable in AppController beforeRender() function,and set that variable,then you can access easily that variable anywhere in the view files

function beforeRender() {
    parent::beforeRender();
    $sample_arr = array("abc","xyz");
    $this->set('sample_arr',$sample_arr);
}

In your Layout File Just Print that Array like

print_r($sample_arr);

1 Comment

Is it safe to go like that?
0

from here:

cakephp set function

// First you pass data from the controller:

$this->set('color', 'pink');

// Then, in the view, you can utilize the data:
?>

You have selected <?php echo $color; ?> icing for the cake.

So for your situation:

$arr = array('stuff', 'more stuff');

$this->set('arr', $arr);

// then in the layout
print_r($arr);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.