user1994811
user1994811

Reputation: 1

How to divide with PHP.

I'm trying to divide in PHP, but I don't get the correct answer when I echo it out.

<?php
$names = file('rating.txt');

// To check the number of lines 
echo "In the textfile: " . count($names).'<br>';

$sum = 0;

foreach($names as $name)
{
$sum = $sum + $name;
}

echo "Total sum: " . $sum;

?>

I tried:

($sum/$name)

But that gives me the wrong result. If I try:

($sum/$names)

I get the following error message:

Fatal error: Unsupported operand types in C:\xampp\htdocs\lab5\rating\index.php on line 55

How do I get the $sum divided by the number of lines I have in the text file?

Upvotes: 0

Views: 481

Answers (1)

Mooseman
Mooseman

Reputation: 18891

Change $sum = $sum + $name; to $sum .= intval($name);. intval converts the string into a number.

If this does not work, the problem is with rating.txt, which you are not showing. ($sum/$names) won't work because you can only divide a number by a another number (Which should be non-zero).

Upvotes: 1

Related Questions