BlackPanther
BlackPanther

Reputation: 1

redeclaration error for function to truncate a string in php

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

Upvotes: 0

Views: 68

Answers (2)

Mat
Mat

Reputation: 13

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 = '...') {
    return strlen($string) > $length 
        ? rtrim(substr($string, 0, strrpos(substr($string, 0, $length + 1), ' '))) . $ellipsis 
        : $string;
}

$string = 'The quick brown fox jumps over the lazy dog';
$truncatedText = truncateString($string, 20);

echo $truncatedText;

Upvotes: 0

Honk der Hase
Honk der Hase

Reputation: 2488

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.

Upvotes: 0

Related Questions