Skip to content
Related Articles

Related Articles

Program to swap two integer parameters using call by value & call by address in PHP ?

View Discussion
Improve Article
Save Article
Like Article
  • Last Updated : 26 Apr, 2022

Call by value:  In call by value, we will send the value from the calling function to the called function. The values of the calling function arguments are directly copied to the corresponding arguments of the called function. If any modification is done on the arguments of the called function, it will not be effected on the arguments of the calling function because the calling function arguments and the called function argument will be represented in different memory locations.

Example:

PHP




<?php
   
function sum($x) {
    $x = $x + 10;
    echo "The sum is $x<br>";
}
      
// code
$n = 20;
sum($n);
  
echo "</br>";
echo "value of n is $n";
      
?>

Output:

The sum is 30

value of n is 20

Call by Reference: In the Call by reference mechanism, the address of a variable will be sent from the calling function to the called function. The corresponding addresses of the calling function arguments will be directly copied into the called function argument. Any modifications done to the called function arguments will be effected on the calling function arguments because both the arguments of the calling function and the called function represent the same memory location.

Example:

PHP




<?php
      
function sum(&$x) { 
      $x = $x + 10;
      echo "The sum is $x";
}
  
$n = 20;
sum($n);
echo"<br> value of n is $n";
  
?>

Output:

The sum is 30
value of n is 30

Swapping of two numbers using call by value:

PHP




<?php
     
function swap($x, $y) {
    $temp = $x;
    $x = $y;
    $y = $temp;
    echo "The value of x is:".$x."<br>";
    echo "The value of y is:".$y."<br><br>";
}
  
$a = 10;
$b = 20;
swap($a, $b);
echo "The value of a is :".$a."<br>";
echo "The value of b is :".$b."<br>";
  
?>

Output:

The value of x is:20
The value of y is:10

The value of a is :10
The value of b is :20

Swapping of two numbers using call by reference:

PHP




<?php
  
function swap(&$x, &$y) { 
    $temp = $x;
    $x = $y;
    $y = $temp;
    echo "The value of x is: ".$x."<br>";
    echo "The value of y is: ".$y."<br><br>";
}
  
$a = 10;
$b = 20;
swap($a, $b);
echo "The value of a is: ".$a."<br>";
echo "The value of b is: ".$b."<br>";
  
?>

Output:

The value of x is: 20
The value of y is: 10

The value of a is: 20
The value of b is: 10

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!