You have to return the another_array inside the function:
The variables declared inside a function are local-only, and the variables declared outside aren't accessible.
$array = array(5 => 1, 12 => 2);
$another_array = make_another_array($array);
print_r($another_array);
function make_another_array(array $array) {
$another_array = array();
foreach ($array as $key=>$value) {
$another_array[$key] = $value;
}
return $another_array;
}
alternatively, you could also pass another array by reference:
$another_array = array();
$array = array(5 => 1, 12 => 2);
make_another_array($array, $another_array);
print_r($another_array);
function make_another_array(array $array, &$another_array) {
foreach ($array as $key=>$value) {
$another_array[$key] = $value;
}
}
or, you could set them inside the function using the global keyword (but I'd recommend using the other two solutions):
$another_array = array();
$array = array(5 => 1, 12 => 2);
make_another_array($array);
print_r($another_array);
function make_another_array(array $array) {
global $another_array;
foreach ($array as $key=>$value) {
$another_array[$key] = $value;
}
}
and finally you could use the superglobal $GLOBALS, which is accessible in all scopes. (which is pretty the same as the sollution above)
$another_array = array();
$array = array(5 => 1, 12 => 2);
make_another_array($array);
print_r($another_array);
function make_another_array(array $array) {
foreach ($array as $key=>$value) {
$GLOBALS['another_array'][$key] = $value;
}
}
return,echo,print_ror similar. Also, there is no reason to create the variable outside the function, it won't be available inside the function, unless you pass it to the function via an option on calling the function, or make it global within the funciton.