PHP Reference Operator(&) with example

Reference operator:
Reference operator(&) introduced in php 4.0 version.

Why we need reference operator ?
Consider this is the scenario,
We have variable a and b. Variable a value assigned to variable b. If we are changing the variable a value frequently after the value assignment to variable b, it will not be reflected.

To overcome the above issue reference operator introduced in php.

Sample PHP Program: [without Reference operator]

<?php
$a = 5;
$b = $a;
$a = 10;
echo $b;
?>

Output:

5

Here we have assigned a variable a value to variable b. But after the assignment variable a value has been changed from 5 to 10. But if you print b variable, we are getting the old assigned value (5) only.

Now the above issue has been resolved using the reference operator in php,

Sample PHP program: [with Reference operator]:

<?php
$a = 5;
$b = &$a;
$a = 10;
echo $b;
?>

Output:

10 (ten)

Here whenever the variable value a changes it affects automatically to the already assigned variable b too.

PHP Recommended Books:

414 total views, 1 views today

Leave a Reply

Your email address will not be published. Required fields are marked *