PHP - How to pass a global variable to a function

I have a function that populates an array that was created before the function started. To make the population work, I used the "global" in my function. Everything works fine with the situation below:

$parameter = 'something';  
$listOne = array();

my_function($parameter);

function my_function($para) {
     global $listeOne;
     ...some code  
     $listeOne[0] = 'john';
     $listeOne[1] = 'lugano';
}

I would like to pass an array to be used in the function when calling the function. The idea would be:

$parameter = 'something';  
$listOne = array();
$listTwo = array();

my_function($listOne, $parameter);
...some code
my_function($listTwo, $parameter);

function my_function($list, $para) {
     ...some code
     $list[0] = 'john';
     $list[1] = 'lugano';
}

Also, according to what I read, using the global is probably not the best ... I saw some people use and sign somewhere and say it is better. But I do not understand and do not find information about this "method" ... I hope I understand. Thank you in advance for your answers. Greetings. Mark

+5
source share
4

:

$listOne = array();

function my_function(&$list, $para) {
     ...some code
     $list[0] = 'john';
     $list[1] = 'lugano';
}
my_function($listOne, $parameter);

print_r($listOne); // array (0 => 'john', 1 => 'lugano');

.

+9

Use &means pass by reference .

For instance:

$x = '123';

function changeX(&$data){
   $data = '1';
}

echo $x; //x should print out as 1.

In your case, you can use:

$parameter = 'something';     
$listOne = array();   
$listTwo = array();   

my_function($listOne, $parameter);   
my_function($listTwo, $parameter);   

function my_function(&$list, $para) {   
     $list[0] = 'john';   
     $list[1] = 'lugano';   
}   
+1
source

you can write your function as follows:

$listOne = array();
my_function($list = array())
{
array_push($list, 'john');
array_push($list, 'lugano');
return $list;
}  

$listOne = my_function($listOne);
print_r($listOne);
+1
source

All Articles