Florian Wenin
Florian Wenin

Reputation: 11

PHP Read a number from a txt file and make then calculations

I have a file which has only one line, with a number from 1 to 40, and I have the following code:

$file_line = file('../countersaver.txt');
foreach ($file_line as $line) {
    $line_result = $line;
}

echo $line;

I have to calculate the result of $line - 1 and echo that result.

But when i do:

$line = $line - 1;

Then it shows $line - 1 and doesn't actually do the calculation.

Upvotes: 1

Views: 10122

Answers (4)

imran
imran

Reputation: 11

I don't see an approved answer here but for anyone looking at this post, if you have a variable that you want PHP to read as a number you can use intval() function. Details covered here...

http://php.net/manual/en/function.intval.php

Upvotes: 1

user4628565
user4628565

Reputation:

Try this:

 $fin = @fopen("path to file", "r"); 

 if ($fin) { 
    while (!feof($fin)) { 
       $buffer = fgets($fin);         
    } 

    fclose($fin); 
 }

Upvotes: 0

MatisDS
MatisDS

Reputation: 163

Try replacing

$line = $line - 1;
echo $line

with

$line = ($line -1);
echo $line

This will print 19 instead of 20-1.

Upvotes: 1

Ranty
Ranty

Reputation: 3362

Your code is weak to changes of the file contents. If someone adds a few blank lines, for example, your code won't work. Try this out instead:

$number = trim(file_get_contents('../countersaver.txt'));
echo $number - 1;

Upvotes: 2

Related Questions