Search code examples
phpblank-line

Deleting/excluding empty lines from being saved and used in PHP


I'm currently fighting with excluding empty lines to be saved into the array $presidents (and by doing that, solving a problem where the foreach loop echoes the strings without Names).

I've tried a few things which should have worked, in my amateur opinion of course (preg_match(), trim(), etc.).

Can someone help me with this?

$file = fopen("namen2.txt", "r");
$presidents = array();
$count = count(file("namen2.txt"));
for($i = 1; $i <= $count;){
    $file_line = fgets($file);
    $line = explode(" ", $file_line);
    $president = array();
    $president["firstname"] = $line[0];
    if(empty($president["firstname"] == false)){
        $president["lastname"] = $line[1];
        $president["counter"] = $i;
        $presidents[] = $president;
        $i++;
    }
    else{echo "fehler";}
}
foreach($presidents as $president_order){
    echo "Hey ". $president_order["firstname"]. " ". $president_order["lastname"]. ", du bist der ". $president_order["counter"]. ". Präsident der USA in meiner Liste. \n";
}

Edit: I've solved my problems by changing conditions and controlling my input at the insertion phase, thanks for the great tips!


Solution

  • You should be dealing with spaces and unwanted characters at the insertion phase of the data, not after it so you should go back to that code and clean the data before the insertion takes place.

    Using PHP's trim should work, there's no reason why it should not work for you. If you have a variable holding a string like " Firstname Lastname " then using that function will turn it to "Firstname Lastname".

    It seems you are splitting each piece of data with spaces... that's not a good idea considering your data may possibly have to include spaces (First names can have spaces too, Mary Jane for example).