Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Php: How to limit the number of rows returned while fetching values from a text file?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

    
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading