Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

Henrik Christensen
seal-mask
.a{fill-rule:evenodd;}techdegree
Henrik Christensen
Python Web Development Techdegree Student 38,322 Points

Why do I get a notice here?

Hi,

I'm trying to truncate large strings to the n-number words. I found this function on stackoverflow and thought I would try it out:

function limit_text($text, $limit) {
    if (str_word_count($text, 0) > $limit) {
        $words = str_word_count($text, 2);
        $pos = array_keys($words);
        $text = substr($text, 0, $pos[$limit]) . '...';
    }
    return $text;
}

I already know what $limit I want and it's going to be the same everywhere so I thought I would try to modify the function a bit, but then I get a notice Undefined offset and I have no idea why?

My version:

// it is working but getting a notice undefined offset
function truncate_words($text) {
    $words = str_word_count($text, 2);
    $position = array_keys($words);
    $truncatedString = substr($text, 0, $position[50]) . "...";
    return $truncatedString;
}

1 Answer

Hi Henrik,

The notice would indicate that index 50 is not defined for the $position array. Are you by any chance getting this notice when the text doesn't have more than 50 words in it?

The original code had a conditional check to make sure there was enough words to require truncation.

This is absent from your revised code. Your revised code is making the assumption that truncation will always be required. But I think you will get that notice if you tried it with text that contained only 15 words for example.

So I think that you'll need to put the conditional check back in to make sure you have enough words.

If the issue is that you're having to put in 50 as the second argument most or all of the time then you could use a default value for that argument.

function limit_text($text, $limit = 50) {

This way you can keep that original working code and you don't have to pass in 50 all the time.

Henrik Christensen
seal-mask
.a{fill-rule:evenodd;}techdegree
Henrik Christensen
Python Web Development Techdegree Student 38,322 Points

Are you by any chance getting this notice when the text doesn't have more than 50 words in it? - I think this might be the problem, because there is 1 post with less word (just noticed) :-P

Ohh yeah, I forgot about default values.

Thank you very much, Jason :-D