How to update reference argument in functions in php?

by raven_corwin , in category: PHP General , 10 months ago

How to update reference argument in functions in php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by aubrey , 10 months ago

@raven_corwin 

In PHP, you can update the value of a reference argument in a function by directly modifying the variable inside the function.


Here's an example:

1
2
3
4
5
6
7
8
9
function updateReferenceArgument(&$arg) {
    $arg = "Updated value";
}

$variable = "Original value";
echo $variable; // Output: Original value

updateReferenceArgument($variable);
echo $variable; // Output: Updated value


In the example above, the updateReferenceArgument function takes a reference argument with the & symbol before the parameter name (&$arg). This indicates that any changes made to the $arg variable inside the function will also affect the original variable that was passed in.


Then, inside the function, you can update the reference argument by assigning a new value to it ($arg = "Updated value"). This will modify the original variable that was passed in.


After calling the updateReferenceArgument function with the $variable argument, you can see that the value of $variable has been updated to "Updated value" outside the function as well.


Note that when passing a variable as a reference argument, you need to use the & symbol in both the function definition and the function call.