Reference Parameters in PHP
It is possible to make a change to a function parameter lead to a change of the parameter outside the function. To do this, the function parameter should be declared as a reference:
<?php
function func(&$num)
{
$num = 2;
}
$num = 1;
func($num);
echo $num; // 2
?>
Correct the following code so that the variable changes inside the function:
<?php
$num = 1;
function func($num)
{
$num++;
}
func($num);
echo $num; // should output 2
?>
Correct the following code so that the array changes inside the function:
<?php
$arr = [1, 2, 3, 4, 5];
function func($arr)
{
$arr[0] = '!';
}
func($arr);
var_dump($arr);
?>