9

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • You should put what the constant 'SIZE' is equal to. It'll make running this a bit easier, so we're in the same ballpark. – Tango Bravo Feb 21 '12 at 15:47
  • A function to crop text? Could you explain a bit more what your trying to accomplish with this function? – tcables Feb 21 '12 at 15:49
  • You are right. Sorry about that. SIZE = 9 and FONTURL = '/usr/share/fonts/dejavu/DejaVuSans.ttf' –  Feb 21 '12 at 15:54

2 Answers2

19

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;
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Marc B
  • 356,200
  • 43
  • 426
  • 500
  • 1
    Thank you. This works fine. I have never done 'real world' recursive function, so this is all new for me. The first solution you suggested works like a charm. –  Feb 21 '12 at 15:57
3

Return the result of your recursive function call ;)

return check_length(substr($str, 0, -1), $max, $size, true);
matzino
  • 3,544
  • 1
  • 18
  • 37