Sunday, June 9, 2013

PHP : Add Item on array

So I got this problem that I encounter today.
Heres the code


$list_items = array(
array('label'=>'Dashboard'),
array('label'=>'Home','icon' => 'home', 'url'=>'#'),
array('label'=>'Residents', 'url'=>Yii::app()->createUrl('residents')),
array('label'=>'Users', 'url'=>Yii::app()->createUrl('users')),
array('label'=>'Reports'),
array('label'=>'Population Growth', 'url'=> Yii::app()->createUrl('residents/chart/population_growth')),
array('label' => 'Population by Year','url' => Yii::app()->createUrl('residents/chart/population_by_year')),
array('label' => 'Distribution of Population','url' => Yii::app()->createUrl('residents/chart/distribution_population'))
);
foreach ($list_items as $item) {
if ($item['label']===$selected_menu) {
$item['active']=true;
}
}

Code says that if the $selected_menu is equal to the label add an new item with key 'active' and a value of true.




First , ofcourse it doesnt work . 
After reading few comments  , turns out that I need to pass by reference to add new item on the $list_items , through the use of &     *yes thats an ampersand character




The working code now looks like this 



$list_items = array(
array('label'=>'Dashboard'),
array('label'=>'Home','icon' => 'home', 'url'=>'#'),
array('label'=>'Residents', 'url'=>Yii::app()->createUrl('residents')),
array('label'=>'Users', 'url'=>Yii::app()->createUrl('users')),
array('label'=>'Reports'),
array('label'=>'Population Growth', 'url'=> Yii::app()->createUrl('residents/chart/population_growth')),
array('label' => 'Population by Year','url' => Yii::app()->createUrl('residents/chart/population_by_year')),
array('label' => 'Distribution of Population','url' => Yii::app()->createUrl('residents/chart/distribution_population'))
);

#heres the solution, using the ampersand
foreach ($list_items as &$item) {
if ($item['label']===$selected_menu) {
$item['active']=true;
}

}


No comments:

Post a Comment