PHP recursive function return value

user1029650 picture user1029650 · Feb 21, 2012 · Viewed 8.4k times · Source

I have written a recursive function in PHP to crop text. The cropped text will have ... attached to the end. Non-cropped text will be returned in its original state.

It works if the text fits the max width. However, if it does not fit in the given width the function will not return a value but it should. It seems that the whole return statement is ignored. If I replace the return with echo, it shows the correct value.

The expected result:
-TEST ZIN
-TEST ZI
-TEST Z
-TEST
-TES
-TE... (nothing is returned here so this will never be shown)

function check_length($str, $max, $size = SIZE, $rec = false) {
    echo "FUNCTION $str ";
    list($left, , $right) = imageftbbox($size, 0, FONTURL, $str);
    if($rec == false) {
        if(($right - $left) > $max) {
            echo 'if 1<br />';
            check_length(substr($str, 0, -1), $max, $size, true);
        } else {
            echo 'else 1<br />';
            return $str;
        }
    } else {
        if(($right - $left) > ($max - 9)) {
            echo 'if 2<br />';
            check_length(substr($str, 0, -1), $max, $size, true);
        } else {
            echo 'else 2<br />';
            return "$str...";
        }
    }
}

echo check_length('TEST ZIN', 30);

NOTE: the echo's in the function are for debugging.

Thank you in advance.

Answer

Marc B picture Marc B · Feb 21, 2012

You're not returning the text properly e.g.

    } else {
        echo 'else 1<br />';
        return $str;   <---nothing in the 'parent' caller catches this, so it's lost
    }

Anywhere you do recursion and need to return a value, you must capture/return the recursive call itself:

    return check_length(substr($str, 0, -1), $max, $size, true);

or

    $newstr = check_length(...);
    return $newstr;