Output problem- "Notice: A non well formed numeric value encountered in (file location).php on line 28

I’m getting this error 3 times. Here’s the code:


<?php
		$wageFile = fopen("wages1.txt","r");	// open the file containing employee wages
		$wage1 = fgets($wageFile);		// read the first wage from the file
		$wage2 = fgets($wageFile);		// read the second wage from the file
		$wage3 = fgets($wageFile);		// read the third wage from the file
		fclose($wageFile);

		$totalWages = $wage1 + $wage2 + $wage3;
		$avgWage = $totalWages/3;

		print("<p>Wage #1: $$wage1<br>");
		print("Wage #2: $$wage2<br>");
		print("Wage #3: $$wage3</p>");
		print("<p>TOTAL WAGES PAID: $$totalWages</p>");
		print("<p>AVERAGE WAGE:     $$avgWage</p>");
	?>

And my ouptut is:

WAGE REPORT

Notice : A non well formed numeric value encountered in D:\XAMPP\htdocs\webtech\coursework\chapter06\fixit1.php on line 28

Notice : A non well formed numeric value encountered in D:\XAMPP\htdocs\webtech\coursework\chapter06\fixit1.php on line 28

Notice : A non well formed numeric value encountered in D:\XAMPP\htdocs\webtech\coursework\chapter06\fixit1.php on line 28

Wage #1: $230.55
Wage #2: $450.65
Wage #3: $310.45

TOTAL WAGES PAID: $991.65

AVERAGE WAGE: $330.55

Line 28 is $totalWages = $wage1 + $wage2 + $wage3; . Please help! :slight_smile:

The errors are due to the new-line characters on the end of the values.

Whoever made this assignment should have also covered the requirements and downfalls associated with storing data in files, such as the need for file locking and the need to trim/cast numbers so that characters that are part of organizing the data as lines in a file get removed before you try to use the values.

Thanks! should the <p> & </p> markers have been outside of the print lines, and the <br> markers moved outside of the quotes, or elsewhere?

Asking this again, to clarify: which new-line characters, and what should I do with them? Or, is there anything that can be done, i.e. is this just a bug in the php version?

fgets() will return a line from your file as a string. Since every line in a file ends with a “new line” whitespace character, that string includes the “new line” character at the end of the line. You can get rid of this “new line” character by calling rtim() on the output of fgets():

$wage1 = rtim(fgets($wageFile));		// read the first wage from the file
$wage2 = rtrim(fgets($wageFile));		// read the second wage from the file
$wage3 = rtrim(fgets($wageFile));		// read the third wage from the file

As phdr said, that’s only part of the problem. When loading data from a file you should check that the data looks how you expect. If you are expecting numbers, is_numeric() is useful. You should also cast your string to the expected type as soon as you can in your program; PHP is very forgiving with this, but that can lead to some pretty weird bugs if you don’t pay attention.

Sponsor our Newsletter | Privacy Policy | Terms of Service