I have a function that populates an array that was created before the function is launched. To make the population work, I used 'global' in my function. Everything is working fine with the here below situation:
$parameter = 'something';
$listOne = array();
my_function($parameter);
function my_function($para) {
global $listeOne;
...some code
$listeOne[0] = 'john';
$listeOne[1] = 'lugano';
}
What I would like is to pass the array that is supposed to be used in the function when calling the function. The idea would be to do something like this:
$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';
}
In addition according to what I read, using global is maybe not the best thing to do... I saw some people using the & sign somewhere and saying it is better. But I don't get it and not find information about that 'method'... Hope I am clear. Thank you in advance for your replies. Cheers. Marc
4 Answers 4
It's called referencing:
$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');
Now the omitted array will be changed.
4 Comments
referencing is linked, anyway the exact term for this occasion here is Passing by reference Maybe you need some thing like "parameters by reference" http://www.php.net/manual/en/functions.arguments.php
Comments
Using & means to pass by reference.
For example:
$x = '123';
function changeX(&$data){
$data = '1';
}
echo $x; //x should print out as 1.
In your case, you could 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';
}
Comments
you can write your function like this:
$listOne = array();
my_function($list = array())
{
array_push($list, 'john');
array_push($list, 'lugano');
return $list;
}
$listOne = my_function($listOne);
print_r($listOne);