How can PHP be used to truncate a title after a certain length and add ellipsis?

To truncate a title after a certain length and add ellipsis in PHP, you can use the `substr()` function to limit the length of the title and then concatenate an ellipsis at the end. This can be achieved by checking the length of the title and applying the truncation if it exceeds the specified length.

function truncateTitle($title, $maxLength) {
    if(strlen($title) > $maxLength) {
        $truncatedTitle = substr($title, 0, $maxLength) . '...';
        return $truncatedTitle;
    } else {
        return $title;
    }
}

// Example usage
$title = "This is a long title that needs to be truncated";
$maxLength = 20;
echo truncateTitle($title, $maxLength);