phprecursionreturnphp-gd

PHP recursive function return value


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 maximum 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.


Solution

  • 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;