PHP recursive function return value

≯℡__Kan透↙ 提交于 2019-11-29 18:43:33

问题


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.


回答1:


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;



回答2:


Return the result of your recursive function call ;)

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


来源:https://stackoverflow.com/questions/9380434/php-recursive-function-return-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!