PHP: check if empty line ("\n")
is-empty, php
Solution
Your comparisons should look like this (note the use of two equal signs):
if($temperature[0] == "\n"){
Your current code is assigning `"\n"` to `$temperature[1]`, which evaluates true, which is why the `if` condition is executing.
If you would like to use `empty()`, which I suggest you do, change your call to `file()` to:
$display = file($cachename, FILE_IGNORE_NEW_LINES);
Adding the `FILE_IGNORE_NEW_LINES` flag will tell the function not to add newlines (`"\n"`) to the end of the array elements.
Problem
I'm using an API in order to retrieve some temperature and location values in JSON format. I'm writing the output in a plain text cachefile. However a temperature station may fail reporting the temperature value, and in that case my output will be an empty line (\n). I want to handle such case by displaying "N/A" for a non-reporting station. Here's a typical cachefile with the first station reporting temperature and location, and the second station shut down (reporting two empty lines): ``` 27.6 Napoli-Posillipo (an empty line) (an empty line) ``` I tried with: ``` $display = file($cachename); $temperature[0] = $display[0]; $location[0] = $display[1]; $temperature[1] = $display[2]; $location[1] = $display[3]; $temp_avg = (($temperature[0]+$temperature[1])/2); //average temperature if($temperature[0] = "\n"){ //if weather station is not reporting data $temperature[0] = "N/A"; $temp_avg = "N/A"; } if($temperature[1] = "\n"){ $temperature[1] = "N/A"; $temp_avg = "N/A"; } echo "<div id='temperature'><b>".$temperature[0]."</b>°C (".$location[0].") | "; echo "<b>".$temperature[1]."</b>°C (".$location[1].") | "; echo "<b>".$temp_avg."</b>°C (avg) | ".$minutes."m".$secondsleft."s ago</div>"; ``` However I keep getting "N/A" for both stations, even if the first station correctly reports its temperature value. N/A°C (Napoli-Posillipo ) | N/A°C () | N/A°C (avg) | 12m21s ago I tried with fgets() instead of file(), but I got an error: fgets() expects parameter 1 to be resource, string given in [...] on line 54 I also tried using if(empty($temperature[foo])) but it didn't work, because of course \n != empty. Any hints? Thanks in advance