PHP Practical Slip 9 Q.A

Write a PHP script to swap two numbers using a function. (Use Call by value and Call by reference).

<?php
//Swap using Call by Value
function swapByValue($a, $b) {
    $temp = $a;
    $a = $b;
    $b = $temp;
    echo "Inside swapByValue: a = $a, b = $b<br>";
}

// Swap using Call by Reference
function swapByReference(&$a, &$b) {
    $temp = $a;
    $a = $b;
    $b = $temp;
}

// Example usage
$x = 10;
$y = 20;

echo "Before swap: x = $x, y = $y<br>";

// Call by Value
swapByValue($x, $y);
echo "After swapByValue: x = $x, y = $y<br>"; // Values remain unchanged

// Call by Reference
swapByReference($x, $y);
echo "After swapByReference: x = $x, y = $y<br>"; // Values swapped
?>
Spread the love

Leave a Comment

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

Scroll to Top