akinuri akinuri - 4 months ago 13
PHP Question

Create a global variable if argument provided

How do I create a global variable the way preg_match does for the

$matches
parameter?

In the following code,
preg_match
creates global
$Hel_matches
and
$Wor_matches
variables even though they're not defined.

$string = "Hello, World!";

$pattern1 = '/Hel/';
$pattern2 = '/Wor/';

preg_match($pattern1, $string, $Hel_matches);
preg_match($pattern2, $string, $Wor_matches);

print_r($Hel_matches);
print_r($Wor_matches);


I want to be able to do the same thing.

For example,
odd_numbers()
returns an array filled with the odd numbers between
0
and
$max
.

function odd_numbers($max) {
$numbers = [];
for ($i = 0; $i <= $max; $i++) {
if ($i % 2 == 1) {
$numbers[] = $i;
}
}
return $numbers;
}

$odd_numbers = odd_numbers(10);
print_r($odd_numbers);


If I want to do some extra calculation in the
odd_numbers()
and also return that (for debug purposes, for example), well, I can't. I can only return one thing. So, instead, I pass a second argument (variable) to the
odd_numbers()
and the function returns/assigns the return value to that variable.

// $odd_numbers = odd_numbers(10, $evens); // fill $evens (if provided) with even numbers for debug purposes
print_r($odd_numbers);
// print_r($evens); // debug

Answer

You can use a reference by prefixing the variable with &:

function odd_numbers($max, &$evens = array()) {
    // blah
    $numbers = array(1, 3, 5);

    if (func_num_args() == 2) {
        $evens = array(2, 4, 6);
    }

    return $numbers;
}

$odd_numbers = odd_numbers(10, $evens);
var_dump($evens);

Output:

array (size=3)
  0 => int 2
  1 => int 4
  2 => int 6