skip to Main Content

At the moment, I’m programming on a blog website where several blog posts will be listed!
For the first post it’s already working with the attached code snippet but unfortunately not for all the following ones!

I’ve got following error: "Fatal error: Cannot redeclare truncateString()" for the code below:

function truncateString($string, $length, $ellipsis = '...') {

    if (strlen($string) <= $length) {
        return $string;
    }

    $truncatedString = substr($string, 0, $length);
    $lastSpace = strrpos($truncatedString, ' ');

    if ($lastSpace !== false) {
        $truncatedString = substr($truncatedString, 0, $lastSpace);
    }

    return $truncatedString . $ellipsis;
}

$string = $post['body'];
$truncatedText = truncateString($string, 200);

echo $truncatedText;

Do you you have any recommendations, ideas how to solve it?

I would love to get it working for all the posts and featured posts on the website!

enter image description here

2

Answers


  1. As said in other replies, this means you have a function declared with the same name.

    By the way, you could simplify your function like that :

    function truncateString($string, $length, $ellipsis = '...') {
    
        $truncatedString = trim(substr($string, 0, $length));
    
        return $truncatedString . ((strlen($string) > $length) ? $ellipsis : '');
    }
    
    $string = 'The quick brown fox jumps over the lazy dog';
    $truncatedText = truncateString($string, 20);
    
    echo $truncatedText;
    
    Login or Signup to reply.
  2. If you’re unsure about how the file was included, you can surround the declaration with a "guard code"

    if (!function_exists('truncateString')) {
        function truncateString($string, $length, $ellipsis = '...') {
            // the code
        }
    }
    

    That way you should not have a problem with multiple include instead of include_once.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search