Reference Examples
This page was last reviewed on Jun 8, 2023.
Dot Net Perls
Reference. In PHP we often have complex collections like arrays that may be difficult to use. We can use references to more easily test and mutate arrays.
With a reference we can avoid indexing the array repeatedly, and just use a variable. This can simplify programs. Often functions can benefit from reference parameters.
Function example. Here we see a function that receives a variable reference argument. When modify() assigns the reference, this changes the variable at the calling location.
Result The value changes from "red" to "blue" after modify is called, and the string ends up with the value "blue."
function modify(&$color) { // Modify a function parameter that is a reference. $color = "blue"; } $test = "red"; modify($test); // This is now modified. var_dump($test);
string(4) "blue"
Variable example. Creating references to variables like integers is probably less useful in PHP programs, but it helps illustrate the concept.
Step 1 We create an "alias" variable and use it to reference the "value" variable, which is equal to 10.
Step 2 We assign a new value 20 to the alias variable. This is reflected in the "value" variable.
Step 3 The var_dump statement prints 20 because the original value was changed from 10 to 20 through an assignment to the reference.
// Step 1: create a variable and an alias (reference) to it. $value = 10; $alias =& $value; // Step 2: modify the variable through the reference variable. $alias = 20; // Step 3: the original was changed by modifying the reference. var_dump($value);
Array element. Suppose we want to act upon an array element. For clearer code, we can reference the array element and use the reference directly.
Step 1 We create an array of 3 strings. The string "red" is at index 1 (the second element).
Step 2 We acquire a reference to the second element in the array (which is equal to "red").
Step 3 We modify the array by assigning to the reference. When printed out, we can see the array now contains "crimson."
// Step 1: create an array of strings. $colors = ["blue", "red", "orange"]; // Step 2: get a reference to the second element in the array. $red =& $colors[1]; var_dump($red); // Step 3: modify the array through the reference variable. $red = "crimson"; var_dump($colors);
string(3) "red" array(3) { [0]=> string(4) "blue" [1]=> &string(7) "crimson" [2]=> string(6) "orange" }
By creating references in our PHP programs, we can make functions more powerful. And we can change elements in arrays with simpler syntax.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jun 8, 2023 (new).
© 2007-2024 Sam Allen.