How do I not run code in loop for items producing "Undefined offset: 0"?
<p>I'm trying to create my own search engine for a site I'm working on and I'm through the "title" and "description" field from a DB table containing a keyword and displaying the results. That works fine, but I wanted to get the page to display only the text around that keyword in the "description" result. I found a some code on StackOverflow (w00t!) to do this:</p>

<pre><code>$string = $s-&gt;description;
$word = $item;
preg_match("/(\w+)? ?(\w+)? ?(\w+)? ?(\w+)? ?(\w+)? ?$word ?(\w+)? ?(\w+)? ?(\w+)? ?(\w+)? ?(\w+)?/i",$string,$result);
$description = preg_replace("/$word/","&lt;B&gt;$word&lt;/B&gt;",$result[0]);
</code></pre>

<p>The problem is that this produces:</p>

<pre><code>A PHP Error was encountered
Severity: Notice
Message: Undefined offset: 0
Filename: search/search.php
Line Number: 21
</code></pre>

<p>Line #21:</p>

<pre><code>$description = preg_replace("/$word/","&lt;B&gt;$word&lt;/B&gt;",$result[0]);
</code></pre>

<p>(From the above code.) But it only does this for some of the results. I haven't figured out what the bad ones have in common yet, but it's like 1 in 4 that don't work.</p>

<p>The solution I tried was to do a check in my foreach loop to see if the variable $description isset(). (Nice pun huh?) </p>

<pre><code>if( !isset($description) ) {
    if(strlen($s-&gt;description) &gt; 200) { 
        $description = substr($s-&gt;description, 0, 200).'...'; 
    } else { 
        $description = $s-&gt;description; 
    } 
}
</code></pre>

<p>Otherwise the variable is already defined above. This however does nothing different than doing no check and just echo-ing out $description as it is defined up top (producing the error).</p>

<p>I have searched "undefined offset: 0" and got a little overwhelmed by the programming terminology (of which I am only beginning to understand now). </p>

<p>I would greatly appreciate some kind of check that actually works or an alternative, because this is confusing the heck out of me. </p>
