1

This function returns NULL while $alias having a value in the second recursion.

In the first call, it returns the required value, but when the first if does not match and it recurse first, the required value is available in the $alias variable, but it does not return anything.

public function checkAlias($fname='', $lname='') {

    if(!empty($fname)) {
        $fname = mysql_real_escape_string($fname);
    }

    if(!empty($lname)) {
        $lname = mysql_real_escape_string($lname);
    }

    $alias = strtolower($fname).strtolower($lname);
    $sql = "Select ALIAS from table where ALIAS = '$alias'";
    $query = mysql_query($sql);
    $row = mysql_fetch_row($query);
    $string_length = strlen($alias) - 1;
    $result_string = substr($alias, 0, $string_length);

    if(!$row) {
        print $alias;   // Is printing value
        return $alias;  // But here it returns null
    }
    else {
        $this->checkAlias($result_string);
    }

}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
rAVi
  • 164
  • 2
  • 13

2 Answers2

12

You forgot to return the result of the recursion call:

return $this->checkAlias($result_string);
Gerald Schneider
  • 17,416
  • 9
  • 60
  • 78
3

You forgot the return keyword before $this->checkAlias($result_string);

Change your code to this:

public function checkAlias($fname='', $lname='') {

    if(!empty($fname)) {
        $fname = mysql_real_escape_string($fname);
    }

    if(!empty($lname)) {
        $lname = mysql_real_escape_string($lname);
    }

    $alias = strtolower($fname).strtolower($lname);
    $sql = "Select ALIAS from table where ALIAS = '$alias'";
    $query = mysql_query($sql);
    $row = mysql_fetch_row($query);
    $string_length = strlen($alias) - 1;
    $result_string = substr($alias, 0, $string_length);

    if(!$row) {
        print $alias;   // Is printing value
        return $alias;  // But here it returns null
    }
    else {
        return $this->checkAlias($result_string);
    }
}

Because the first time the code will reach the else statement, and the second time it runs it will go in the if statement. The if returns the value, but in the else you don't do anything with it, so it returns it and you get your value.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Stefan Koenen
  • 2,289
  • 2
  • 20
  • 32