I am fetching data from a text file. How do I limit the number of returned results? I only want the array to echo the top 10 most relevant results based on the searchfor value.
Script provided by @Shlomtzion
<?php
$text = "I0023540987805R01 ABC GHI
0000002032902R01 DEF JKL
I0023540987805R01 LMNO PQR ";
echo '<pre>';
$txt = explode("\n",$text);
echo '<pre>';
print_r($txt);
foreach($txt as $key => $line){
$subbedString = substr($line,2,11);
$searchfor = '02354098780';
//echo strpos($subbedString,$searchfor);
if(strpos($subbedString,$searchfor) === 0){
$matches[$key] = $searchfor;
$matchesLine[$key] = substr($line,2,11);
//how do I limit the return result to 10 rows of data?
echo "<p>" . $matchesLine[$key] . "</p>";
}
}
?>
>Solution :
You could use a counter and a break statement
<?php
$text = "I0023540987805R01 ABC GHI
0000002032902R01 DEF JKL
I0023540987805R01 LMNO PQR ";
echo '<pre>';
$txt = explode("\n",$text);
echo '<pre>';
print_r($txt);
$counter = 0;
foreach($txt as $key => $line){
$subbedString = substr($line,2,11);
$searchfor = '02354098780';
//echo strpos($subbedString,$searchfor);
if(strpos($subbedString,$searchfor) === 0){
$matches[$key] = $searchfor;
$matchesLine[$key] = substr($line,2,11);
//how do I limit the return result to 10 rows of data?
echo "<p>" . $matchesLine[$key] . "</p>";
$counter += 1;
if($counter==10) break;
}
}