Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP code Output

Tags:

php

I was studying for my finals and I came across this question:

write the output after running this code.

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

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

I understand exactly what this code does, however after I ran it I got a completely different answer to what I answered with and I really don't understand the output. The output I got was 3, 206, 36.

Could someone explain the output to me?

like image 415
Pro-grammer Avatar asked Feb 21 '23 18:02

Pro-grammer


2 Answers

What you get is actually 3, 20, 6, 36 which is the correct answer. If you don't understand why you got "206" instead of "20" and "6" it is just because you have not a space after the first print. That's it.

like image 107
Aurelio De Rosa Avatar answered Feb 23 '23 07:02

Aurelio De Rosa


first print statement print 3, 20 second print statement print 6,36

first dont get confused in this .. when you pass value by ref, it changes the original value.. thats why it give second output as 6,36

like image 20
Rukmi Patel Avatar answered Feb 23 '23 07:02

Rukmi Patel