Search code examples
phpfunctionvariablesreturnecho

PHP Function that call itself does not return anything


This is not returning anything:

<?php

function cc($i=0) {
    if ($i >= 2) {
       return $i;
    }
    cc($i+1);
}
echo cc(0);

But with echo it's working perfectly:

<?php

function cc($i=0) 
{
    echo $i;
    if($i>=2) {
       return $i;
    }
    cc($i+1);
}
echo cc(0);

Looks preety wierd to my eyes but I'm quite sure there is a logical explanation behind it :)


Solution

  • It doesn't return anything because you missed a return in the recursive call. Use this:

    function cc($i=0) {
      if($i>=2){
        return $i;
      }
      return cc($i+1);
    }
    

    Using ternary operator:

    function cc($i=0) {
      return $i>=2 ? $i : cc($i+1);
    }