1

What is the difference between swap($a, $a) and with an '&' added for swap(&$a, &$a)

<?php 
 function swap($x, $y) { 
 $x = $x + 1; 
 $y = $y + 2; 
 return $x * $y; 
 } 

 $a = 2; 
 $b = swap($a, $a); 
 print "$a, $b"; 
 $b = swap(&$a, &$a); 
 print "$a, $b"; 
?>

Note: not asking for the answer, just wrote this so i could provide an example. Thank You.

niklasfi
  • 15,245
  • 7
  • 40
  • 54
user3364498
  • 489
  • 1
  • 9
  • 14

1 Answers1

1

The & means that the parameter is passed by reference. The question is indeed a duplicate but please be aware that you shouldn't use call-time pass-by-reference anymore.

From the passing by reference page on php.net:

As of PHP 5.3.0, you will get a warning saying that "call-time pass-by-reference" is deprecated when you use & in foo(&$a);. And as of PHP 5.4.0, call-time pass-by-reference was removed, so using it will raise a fatal error.

What you still can do is using the & in the function definition:

function swap(&$x, &$y) { 
    $x = $x + 1; 
    $y = $y + 2; 
    return $x * $y; 
}
Marcel Gwerder
  • 8,353
  • 5
  • 35
  • 60