To more clearly see how the iterator internally works, you can also do it manually (without foreach doing all the magic),as is shown here in the second part of the script:

$details_query = "
SELECT document_id, substr(doc.body, position - 20, 100)
FROM dictionary d, lookup l, document doc
WHERE = l.word_id
AND word in ('$words')
AND document_id IN ($doc_ids)
AND document_id =
GROUP BY document_id, doc.body
$result = $db->unbufferedQuery($details_query, SQLITE_NUM);
while ($result->valid()) {
$record = $result->current();
$list[$record[0]] = $record[1];