Reputation: 578
I am having a problem of Undefined variable when I try to use an array inside a function. An example is the code below. How can I be able to access the array $prev
inside the function hello()
? I've tried searching but I don't really know how to use $GLOBALS[$varname]
when the variable is an array. Thanks for any help!
<?php
$prev = [0,1,2];
function hello(){
echo $prev[1];
}
hello();
hello();
hello();
?>
Upvotes: 2
Views: 13385
Reputation: 1440
You can also pass the variable into the function:
$prev = [0,1,2];
function hello(array $array){
echo $array[1];
}
hello($prev);
hello($prev);
hello($prev);
?>
An other way is to pass the variable by reference.
function hello(&$array){
$array[1]++;
echo $array[1];
}
Upvotes: 8
Reputation: 40681
You could do something like:
$GLOBALS["prev"] = [0,1,2];
function hello(){
echo $GLOBALS['prev'][1];
}
hello();
However consider doing something like:
$prev = [1,2,3];
function hello($prev) {
echo $prev[1];
}
hello($prev);
As an alternative solution:
class GlobalsContainer {
public static $prev=[1,2,3];
}
function hello() {
echo GlobalsContainer::$prev[1];
}
hello();
Upvotes: 4
Reputation: 2217
Declare array with global
keyword inside the function
. See it -
<?php
function hello(){
global $prev = [0,1,2];
echo $prev[1];
}
?>
Upvotes: 0
Reputation: 377
This is the way to use it as global. Btw there are also other ways to use it inside the hello function.
$prev = [0,1,2];
function hello(){
global $prev;
echo $prev[1];
}
hello();
hello();
hello();
Upvotes: 6