I'm working on magento site and facing strange error when array values assign inside function and retrieve outside of function.
//define array
$ctall=array();
//function for array value assign
function printtest($fg){
//global variable
global $ctall;
//just assign to array
$ctall[rand(10000,100000)]=$fg;
//this var dump shows array with vaues when function calling
// var_dump($ctall);
}
i call the function here inside an another function
$categoryTree = Mage::getResourceModel('catalog/category')->getCategories($categoryId, 0, true);
$printCategories = function($nodes) use (&$printCategories) {
foreach ($nodes as $_category):
$ctdf=$_category->getId();
$categoryn = Mage::getModel('catalog/category')->load($ctdf);
if($ctdf!='' && $categoryn->getIsActive()):
//here call to function by passing a value
printtest($ctdf);
$printCategories($_category->getChildren());
endif;
endforeach;
};
$printCategories($categoryTree);
//sleep(10);
// i try to get array results here but it shows empty
var_dump($ctall);
Anyone know how to fix this, i tried hours without luck. Thank You
remove all declaration of $ctall, and try this:
//remove define array, don't define it
// $ctall=array();
function printtest($fg){
if(!isset($GLOBALS['ctall'])){
$GLOBALS['ctall'] = array();
}
//assign to global
$GLOBALS['ctall'][rand(10000,100000)]=$fg;
}
on outside, dump like this:
var_dump($GLOBALS['ctall'])
Try to push instead of assigning.Try this:
$ctall[][rand(10000,100000)]=$fg; //notice the empty square brackets
you can try this also:
function printtest($fg){
global $ctall;
$new_array =array();
$new_array[rand(10000,100000)] = $fg;
array_merge($ctall, $new_array);
}