0

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>";
        }
    
        
    }
    
?>
Jack Yuan
  • 72
  • 11
  • 1
    Have you tried using a counter along with a `break`command to exit the foreach loop once you have returned 10 results? – David Dec 13 '21 at 21:05

1 Answers1

1

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;
    }

    
}
David
  • 1,898
  • 2
  • 14
  • 32
  • Thank you, it worked! btw, the function takes a sec or two to pull the data. Is there a way to optimize this? – Jack Yuan Dec 13 '21 at 21:08