PHP recursive function return value [duplicate]
Asked Answered
P

2

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.

Prioress answered 21/2, 2012 at 15:41 Comment(3)
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.Corcovado
A function to crop text? Could you explain a bit more what your trying to accomplish with this function?Rhizome
You are right. Sorry about that. SIZE = 9 and FONTURL = '/usr/share/fonts/dejavu/DejaVuSans.ttf'Prioress
C
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;
Comely answered 21/2, 2012 at 15:47 Comment(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.Prioress
M
3

Return the result of your recursive function call ;)

return check_length(substr($str, 0, -1), $max, $size, true);
Mcmath answered 21/2, 2012 at 15:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.