Skip to content
Advertisement

Printing upto a specific string when reading from a file in php

I have a text file containing names which i am reading using the file() function in php but when i am trying to stop at certain point when a matching name is found, i am not getting any output. please help.

<?php 
    $data = file('names.txt');
    foreach($data as $val){
       if($val == "Amanda jackson"){
           break;
       }else{
           echo $val;
       }
    }
    
?>

Advertisement

Answer

Add a rtrim() to remove the newline from $val

$data = file('names.txt');
foreach($data as $val){
    if(rtrim($val) == 'Amanda jackson'){
        //if you want to print Amada's name add an echo here
        break;
    }else{
        echo $val;
    }
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement