GeeksforGeeks App
Open App
Browser
Continue

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

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

 `"``;``}``     ` `// code``\$n` `= 20;``sum(``\$n``);`` ` `echo` `"
"``;``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

 ` value of n is \$n"``;`` ` `?>`

Output:

```The sum is 30
value of n is 30```

Swapping of two numbers using call by value:

## PHP

 `"``;``    ``echo` `"The value of y is:"``.``\$y``.``"

"``;``}`` ` `\$a` `= 10;``\$b` `= 20;``swap(``\$a``, ``\$b``);``echo` `"The value of a is :"``.``\$a``.``"
"``;``echo` `"The value of b is :"``.``\$b``.``"
"``;`` ` `?>`

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

 `"``;``    ``echo` `"The value of y is: "``.``\$y``.``"

"``;``}`` ` `\$a` `= 10;``\$b` `= 20;``swap(``\$a``, ``\$b``);``echo` `"The value of a is: "``.``\$a``.``"
"``;``echo` `"The value of b is: "``.``\$b``.``"
"``;`` ` `?>`

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
Related Tutorials