PHP Pass By Reference

PHP Code Snippets Pass By reference
Share:

About

In this code snippet, we’ll learn how to pass and work with variables by reference in PHP.

Variables can be passed either by value or by reference.

Usually, we do it by value meaning you pass just the value and not the variable itself. So, any changes made locally inside the function scope won’t be seen outside of the function scope.

Meanwhile, if we pass a variable as a reference is essentially like passing in the variable itself. Any changes made locally inside the function to the variable will occur outside of the function scope as well.

Let’s see the example code below.

Code:

<?php
$a = 5;
echo "Initial value of a: " . $a;
echo "<br>";
//Pass by value/////////////////////////////////
increment($a);
echo "Value of a after increment(): " . $a;
echo "<br>";
////////////////////////////////////////////////
//Pass by reference/////////////////////////////
incrementByReference($a);
echo "Value of a after incrementByReference(): " . $a;
echo "<br>";
//Passing by reference works the same way with the foreach() loop.
$numbers = [ 10, 5, 6, 7 ];
foreach($numbers as &$number)
$number++;
echo "foreach() pass by reference: ";
echo "<pre>";
print_r($numbers); 
echo "</pre>";
////////////////////////////////////////////////
//Functions////////////////////////////////
function increment($a){
//Here just the value gets passed and a local version of $a gets created. 
$a++;
}
//Use & to make a reference parameter.
function incrementByReference(&$a){
//Here the actual variable is passed as the parameter.
//So any changes made to it in this fucntion will be reflected outside of it.
$a++;
}
////////////////////////////////////////////

Resulting Output:

Share:

Leave a Reply

Your email address will not be published.

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger