Question

<?php
  function a($n){
    return ( b($n) * $n);
  }

  function b(&$n){
    ++$n;
  }

  echo a(5);

  ?>

I did an exam this sunday and would like to know why the output for this code is 0 ?

I'm no developer in php so any help would be appreciated.

Was it helpful?

Solution

The code gives 0 because it is missing a return. Compare with the following which (when corrected as shown) produces 36, as reasoned in the other answer.

function a($n){
  // Since b($n) doesn't return a value in the original,
  // then NULL * $n -> 0
  return ( b($n) * $n);
}

function b(&$n){
  // But if we return the value here then it will work
  // (With the initial condition of $n==5, this returns 6 AND
  //  causes the $n variable, which was passed by-reference,
  //  to be assigned 6 such that in the caller 
  //  it is 6 * $n -> 6 * 6 -> 36).
  return ++$n;
}

echo a(5);

See Passing by Reference for how function b(&$n) works above; if there signature was function b($n) the result would have been 30.

OTHER TIPS

function a($n) {
    return (b($n) * $n);
}

function b(&$n){
    ++$n;
}

echo a(5);

This is what happens when you call echo a(5); (not in the actual order, it's just for demonstration):

return (b($n) * $n);

This return statement has two parts: b($n) and $n. b($n) is a call to the function b. Function b accepts its arguments by reference and increments the value by 1. Note that it doesn't return a value.

Since it doesn't return a value, b($n) will be NULL. Proof:

function a($n){
    $v = b($n);
    var_dump($v);
    return (b($n) * $n);
}

Output:

NULL

In the next step, you multiply the result of b($n) (which is NULL) with $n (which equals to 6).

So the result is NULL * 0. What's the result? Use var_dump():

var_dump(NULL * 6);

Output:

int(0)

Everything will be fine and dandy if you return a value in b:

function a($n){
    return (b($n) * $n);
}

function b(&$n){
    return ++$n;
}

echo a(5);

Output:

36

By default, in PHP, the return statement is equal to NULL / 0. So even if, the b() function changes the value of n by reference, the return statement is equal to null. Then when you multiply this return statement by (equal to zero) by any number, it will equal to zero.

Try to add 'return 1' at the end of the b() definition, the result should be equal to n.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top