How can the issue of unnecessary ellipses (...) be avoided when truncating text in PHP?

When truncating text in PHP, the issue of unnecessary ellipses (...) can be avoided by checking if the length of the text exceeds the desired limit before adding the ellipses. If the text is within the limit, no ellipses are needed. If it exceeds the limit, the text should be truncated and the ellipses added at the end.

function truncateText($text, $limit) {
    if (strlen($text) <= $limit) {
        return $text;
    } else {
        return substr($text, 0, $limit) . '...';
    }
}

// Example usage
$text = "This is a long text that needs to be truncated.";
$truncatedText = truncateText($text, 20);
echo $truncatedText;