PHP Practical Slip 18 Q.A

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

<?php

// Call by Value
function swapValue($a, $b) {
    $temp = $a;
    $a = $b;
    $b = $temp;

    echo "Inside swapValue Function:<br>";
    echo "A = $a <br>";
    echo "B = $b <br><br>";
}

$x = 10;
$y = 20;

echo "<h3>Call by Value</h3>";
echo "Before Swapping:<br>";
echo "X = $x <br>";
echo "Y = $y <br><br>";

swapValue($x, $y);

echo "After Swapping (Outside Function):<br>";
echo "X = $x <br>";
echo "Y = $y <br><br>";


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

$m = 30;
$n = 40;

echo "<h3>Call by Reference</h3>";
echo "Before Swapping:<br>";
echo "M = $m <br>";
echo "N = $n <br><br>";

swapReference($m, $n);

echo "After Swapping (Outside Function):<br>";
echo "M = $m <br>";
echo "N = $n <br>";
Spread the love

Leave a Comment

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

Scroll to Top