PHP: check if empty line ("\n") - php

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

You also can use:
if (trim($temperature[1]) == '') {
// Empty line.
}

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.

Related

I'm getting wrong result in php code where I have to return the total sum of all the numbers from a file

I have to write a function that return the sum of all the numbers in a file.
The text file is numbers.txt:
1
1
2
3
5
8
13
21
The code I write is:
function sumFromFileInput($fileName) {
$total = 0;
$file = fopen("numbers.txt", "r");
while ($number = fgets($file)) {
$total += $number;
}
fclose($file);
return $total;
}
The output should be 54 whereas my output is 124712203354.
Please help me to figure out what I did wrong.
You can use file() for this purpose and simplifiy your code:
$trimmed = file('<provide file path here>', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$sum = array_sum($trimmed);
echo $sum;
In case you added values as string into file then you need to convert them to Integer first.
Add below line before array_sum() line:
$trimmed = array_map('intval', $trimmed);
function sumFromFileInput($fileName) {
$total = 0;
$file = fopen("numbers.txt", "r");
while (!feof($file)) { #this will give you a true value until it reaches end of the numbers.txt last line
$total += (int) fgets($file); # this will read file lines one by one
}
fclose($file);
return $total;
}
What happens if you modify your code to be like this:
function sumFromFileInput($fileName) {
$total = 0;
$file = fopen("numbers.txt", "r");
while ($number = fgets($file)) {
// Making sure to add integer values here
$total += (int)$number;
}
fclose($file);
return $total;
}
I have the feeling that your number values from your input file are being read in as strings instead of ints. Using something like (int) should be able to help with this type of issue. You could also potentially use (integer) or intval() instead of (int) for the conversion part. More info about this can be found here.
Update:
After seeing CBroe's comment, I removed my earlier part about the string concatenation conjecture.
When checking the sumFromFileInput() function locally and using var_dump($number) to show the $number variable's type, I can verify that it is a string. This is why I still recommend using something like (int), like in my added lines of code earlier in this answer. Without doing that, I get PHP notices in PHP 7.3.19 for these values that read like: PHP Notice: A non well formed numeric value encountered in [...].
Interestingly enough, though, I still get a total of 54 (as an int) with your original posted code. This gets me to thinking: it would be interesting to see the code you used to call your sumFromFileInput() function, because perhaps that might help explain why your output was what now appears to me to be a running sum total of the $total.
Also, this might not be as important, but it looks like your $fileName parameter isn't currently being used in your sumFromFileInput() function. Maybe this could be connected in the future?

"If" doesn´t work - weird string formatting

I have weird problem with data handling. I need to pick data from the user form, and handle it (generate xml).
The data is for example this:
2000;AC;1;60;5;5;Do your setup - meaning voltage, voltage type, test current, test time, ramp-up time, rampdown time, and user prompt.
I want to decide how to assemble my xml file based on the last value. If it is zero, there will be shorter xml assembly, while when there is text, there will be user prompt assembly of xml taggery.
So I explode the input into array, and check the value by:
If (empty($xplodline[6]) == true) {do this;}
else {do that;}
The problem is, that it always only does "that", and never "this", even when there is 0 in the $xplodline[6] as intended.
So I put echo $xplodline[6]; into {do that;} to see what´s happening.
The zero is echoed, (and while this action is in the cycle, I get other $xplodline[6]s from the cycle), and I see there is a space between the zero in the $xplodline[6] and next $xplodline[6] iteration. When I look into user form or temporary cleaned file with these values, there is no space between. Where could it come from?
When I put another array divider into the user form to make it ;0; there is no space, and If statement works well.
Here is the original data from the temporary cleaned file:
2000;AC;1;60;5;5;0
2000;AC;1;60;5;5;Set your cables for X10
2000;AC;1;60;5;5;Set your cables for X10
Any idea?
Ok, here is the code:
$stringer = fopen($tempfile, "r");
while(!feof($stringer)){
$oneline = fgets($stringer) ;
$xplodline = explode(";",$oneline) ;
$range01 = "gross" ;
$rampup = "100" ;
$rampdown = "100" ;
$rampupfunction = "false" ;
$rampdownfunction = "false" ;
$currentrange = "_1mA" ;
$assy01 = "1" ;
if ($xplodline[0] >= 3000) {$range01 = "gross" ;}
else {$range01 = "klein" ;}
if (empty($xplodline[4]) == false) {$rampupfunction = "true" ; $rampup = round($xplodline[0] / $xplodline[4]) ;}
if (empty($xplodline[5]) == false) {$rampdownfunction = "true" ;$rampdown = round($xplodline[0] / $xplodline[5]) ;}
if ($xplodline[2] < 1) {$currentrange = "_1mA";}
if ($xplodline[2] >= 1 && $xplodline[2] < 10) {$currentrange = "_10mA";}
if ($xplodline[2] >= 10 && $xplodline[2] < 100) {$currentrange = "_100mA";}
if (empty($xplodline[6]) == true) {$assy01 = $xmltestbegin.$xplodline[0]."V ".$xplodline[1].$xmltype.$xplodline[1].$xmlrange.$range01.$xmlrampup.$rampupfunction.$xmlrampdown.$rampdownfunction.$xmlcurrentrange.$currentrange.$xmlvoltage.$xplodline[0].$xmlrampupspeed.$rampup.$xmlrampdownspeed.$rampdown.$xmltesttime.$xplodline[3].$xmlcurrent.$xplodline[2].$xmlballast ;}
else {$assy01 = $xmlpromptbegin.$xplodline[6].$xmlpromptend.$xmltestbegin.$xplodline[0]."V ".$xplodline[1].$xmltype.$xplodline[1].$xmlrange.$range01.$xmlrampup.$rampupfunction.$xmlrampdown.$rampdownfunction.$xmlcurrentrange.$currentrange.$xmlvoltage.$xplodline[0].$xmlrampupspeed.$rampup.$xmlrampdownspeed.$rampdown.$xmltesttime.$xplodline[3].$xmlcurrent.$xplodline[2].$xmlballast ;}
file_put_contents ( $filename, $assy01, FILE_APPEND );
}
fclose($stringer);
My function works ok, every If except the last one, works...
From http://php.net/manual/en/function.fgets.php
Reading ends when length - 1 bytes have been read, or a newline (which is included in the return value), or an EOF (whichever comes first). If no length is specified, it will keep reading from the stream until it reaches the end of the line.
In short, there's always going to be a newline character in your last array entry. Clean it up by doing
$oneline = rtrim(fgets($stringer));
You can also consider:
$stringer = fopen($tempfile, "r");
while(!feof($stringer)){
$xplodline = fgetcsv($stringer,0,";");
//Rest of code as normal
which would let PHP handle the file as a CSV style file.

adding string and number together in php (FAULT!!)

I'm having little trouble with this code that reads ordernumbers from txt file, then adds 1 to that number. However PHP does not add these numbers together regardless of automatic type-casting...
$handle1 = fopen("ordernumbers.txt", "r");
$numberoforders = fgets($handle1);
$numberoforders = trim($numberoforders);
$orderid=$numberoforders+1;
echo $orderid;
When echoing $numberoforders, it returns number 5 (type is string)
When echoing $orderid, it returns 1, while it should give 6.
I can not see any problem here, and it still does not work. I tried also to change that variable type from string to int, and then add these numbers together, but same result (1).
edit:here's the contents of the txt file:
http://imgur.com/bzjOuOJ
As your var_dump gives string(4) ''5'' to string stored in $numberoforders must contain three more characters.
I suspect a linebreak or something similar
Because $numberoforders is converted into integer and its value is 0, so 0 + 1 =1 that's the output you are getting . If you want the string's characters number add to the integer value, you need to count the string's length first.
You can get your result like so
$handle1 = fopen("ordernumbers.txt", "r");
$numberoforders = fgets($handle1);
$numberoforders = trim($numberoforders);
$numberoforders = strlen($numberoforders);
$orderid=$numberoforders+1;
echo $orderid;

PHP read value cURL page

I'm a fan of Bitcoins and all other alternative coins, so what I am trying to make is a page with all my coins I own, and shows the latest value of each coin.
So what I've got so far is a cURL that gets the content of a website, in this case it is cryptorush.in.
The output of the cURL is:
21 / BTC
13.22000001
42 / BTC
112.10000000
Etc.
So I thought it would be a nice way to recognize "21 / BTC" for example and read the latest value at the next line.
$curlPage is my cURL page.
if (strpos($curlPage,'21 / BTC') !== false) {
//do something
}
Output:
13.22000001
But I really have no idea on how to do this, so I hope anyone could answer my question.
You can use a combination of regexp and the explode function. Please note that this is dependent upon the actual coding of the page you are requesting with cURL, as I am looking at the values being exploded by two returns - \n\n
$curlPage = "21 / BTC \n13.22000001\n\n42 / BTC \n112.10000000";
$arr = explode("\n\n", $curlPage);
foreach($arr as $key)
{
list($top, $bottom) = explode("\n", $key);
$top = preg_replace("/[^0-9]/", "", $top);
if($top == "21") echo($bottom);
}
The first line shows what my value for $curlPage is (for testing it). This should be equal to the contents of the page (provided the contents are what you posted and each section is separated by two line breaks (\n\n)
The two important variables in the foreach() statement is $top and $bottom. $top will be equal to the number, like 21. And the $bottom variable will be equal to the bottom number like 13.22000001

PHP Trying to get strings from array that start with certain letter, giving me everything

I'm trying to get strings from a my_sqli query that only start with a certain letter, however it always outputs the whole array. Here's my code, I'm trying to get the first value, see if it starts with the correct letter, then echo it if it does, then go on to the next.
$strSQL = "SELECT title FROM blogtable ORDER BY title ASC";
$titleResult = mysqli_query($con, $strSQL);
while($rowTitle = mysqli_fetch_array($titleResult))
{
$strTitle = $rowTitle['title'];
$subTitle = substr($strTitle,0,2);
$subNum = ord($subTitle);//This gets me the value of the first letter
if($subNum = $topLetter)//$topLetter = 65, which is capital A
{
echo $strTitle;
echo "<br>";
}
}
So the problem here is that, say if I have 3 things, and only 2 start with A, it will output all 3, but I just want the 2 that start with A.
Change your if statement.
if($subNum == $topLetter)
Explanation: Operator == test for equality and operator = is assignment operator.

Categories