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?
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).
Related
I get this Error for every row in the data. So around 500 times, but every time with an other Undefined offset.
Heres my Code:
$fl_array = preg_grep('/^\d+\s('. $SelectedTime .':)\d+/', explode("\n", $finalLog));
$count = count($fl_array);
for ($x = 0; $x < $count; $x++)
{
echo "$fl_array[$x] \n";
}
as written here - http://php.net/manual/en/function.preg-grep.php: Returns an array indexed using the keys from the input array. so maybe smth wrong with your keys:
if (isset($fl_array[$x])) {
echo "$fl_array[$x] \n";
}
I echo some numbers from the database and show only those numbers with a foreach. I now want to calculate the total of these numbers.
$test = str_replace('\\', '', $orderDetails['jsonData']);
$bonbonOrders = unserialize($test);
foreach($bonbonOrders as $bonbonOrder){
foreach($bonbonOrder as $bonbons){
echo $bonbons['gewicht'];
}
}
I tried several things but I really don't know how I can calculate them.
the output for a example can be:
18 15 16 12 11
Thanks!
This depends how you are getting those numbers from your database. However, since you are deserializing something I will assume that it cannot be done in a simple SQL query.
The following code should echo out the total of all of the numbers.
$test = str_replace('\\', '', $orderDetails['jsonData']);
$bonbonOrders = unserialize($test);
$nums = array();
foreach($bonbonOrders as $bonbonOrder){
foreach($bonbonOrder as $bonbons){
$nums[] =$bonbons['gewicht'];
}
}
$total = array_sum($nums);
echo $total;
Achieved by adding all of the numbers to an array, and calling array_sum on the final array.
Another alternative would have been to create $total = 0 before the foreach and to simply increment it as you get access to each number.
Simply addup each $bonbons['gewicht'] value in a variable and echo it
$test = str_replace('\\', '', $orderDetails['jsonData']);
$bonbonOrders = unserialize($test);
$sum =0;
foreach($bonbonOrders as $bonbonOrder){
foreach($bonbonOrder as $bonbons){
echo $bonbons['gewicht'];
$sum += $bonbons['gewicht'];
}
}
echo $sum;
Im trying to get out an average value from a vote function.
<?php
$file = file("textfile.txt");
$textfil = file_get_contents("textfile.txt");
$textfill = str_split($textfil);
echo "Number of votes: " . count($textfill) . "<br>";
$sum = 0;
foreach ($textfill as $vote) {
$sum = $sum + intval($vote);
}
echo "Average: " . $sum;
?>
Simple by substitute (+) with a (/), and even tried a (%). But still getting error message.
Would appreciate alot if anyone could help me out and tell me what im doing wrong.
/thanks
Edit
Sidenote: Please read an explanation under "First answer given" further down below.
This version will take into account any blank lines in a file, if the content looks like:
1
2
3
// <- blank line
Sidenote: Please provide a sample of your text file. A comment has already been given to that effect.
PHP
<?php
// first line not required
// $file = file("textfile.txt");
$textfil = file_get_contents("textfile.txt");
$textfill = array_filter(array_map("trim", file("textfile.txt")), "strlen");
echo "Number of votes: " . count($textfill) . "<br>";
$sum = 0;
foreach ($textfill as $vote) {
$sum += intval($vote);
}
$avg = $sum / count($textfill);
echo "Average: " . $avg;
?>
First answer given
Using the following in a text file: (since no example of file content was given)
5
5
5
IMPORTANT NOTE: There should not be a carriage return after the last entry.
produced
Number of votes: 5
Average: 3
which is false, since there are 3 entries in the text file.
explode() should be used, and not str_split()
The following using the same text file produced:
Number of votes: 3
Average: 5
which is correct. In simple mathematics, averages are done by adding all numbers then dividing them by how many numbers there are.
In this case it's 3 numbers (all 5's) added equals 15, divided by 3 is 5.
Sidenote: The first line is not required $file = file("textfile2.txt");
<?php
// first line not required
// $file = file("textfile.txt");
$textfil = file_get_contents("textfile.txt");
$textfill = explode("\n", $textfil);
echo "Number of votes: " . count($textfill) . "<br>";
$sum = 0;
foreach ($textfill as $vote) {
$sum += intval($vote);
}
$avg = $sum / count($textfill);
echo "Average: " . $avg;
?>
Footnotes:
If the average comes out to 8.33333 and you would like it to be rounded off to 8, use:
echo "Average: " . floor($avg);
If the average comes out to 8.33333 and would like it to be as 9 you would use:
echo "Average: " . ceil($avg);
ceil() function
floor() function
You may be mixing in stuff that can't be divided, like text, etc. I don't know what your text file looks like. intval may be having a problem with arrays. You may try:
foreach ($textfill as $vote) {
if(is_int($vote) {
$sum += $vote;
}
}
echo "Average: " . $sum;
Lower school math says:
foreach ($textfill as $vote) {
$sum += intval($vote);
}
$avg = $sum / count($textfill);
The average value is calculated by divide the sum with the number of votes. This line will print the average value:
echo "Average: " . $sum/count($textfill);
I'm getting error like PHP
Warning: Division by zero error.
I'm still and want to calculate some problems. If you can tell me, how can calculate antilog / log inverse with examples, I'll be more satisfied.
<?
if(isset($_POST['submit']))
{
$P=$_POST['P']; // P=100000
$rate=$_POST['rate']; // rate = 10.5
$R=($rate/100);
$N=$_POST['N']; // N = 78
echo $P ."<br>" ;
echo $R ."<br>" ;
echo $N ."<br>" ;
$NEW=($R/12); // NEW = .00875
$aa = (1+($NEW)); // aa = 1.00875
$ab = bcpow('$aa', '$N',16); // ab = 1.9729529246182467
$ac = ($ab-1); // ac = 0.9729529246182467
$ad = bcdiv('$ab', '$ac', 3); // Div by Zero Error
$M = ($P*$NEW) *($ad);
echo "The Installment is : " . $M . "<br>";
}
?>
The line with the problem:
$ad = bcdiv('$ab', '$ac', 3); // Div by Zero Error
The problem here is because $ab and $ac are in quotes. They shouldn't be.
Having them in quotes means that PHP sees $ab as being a string consisting of the characters $, a and b, instead of the numeric value of the $ab variable.
Remove the quotes, and it should start working.
The same applies to the bcpow() line.
bcpow('$aa', '$N',16); are you sure these variables get parsed? They are treated as a string in single quotes, and since there is no number they might be just bogus. (typing $aa^$n on a calculator will fail).
You can use bcpow("'".$aa."'", "'".$N."'",16); or try using double quotes.
I didn't understood your code as well, but here is the code that calculate Antilog / log of a value
<?php
$log = 11;
$e = 2.718281828;
$dn = 1;
// Calculate Antilog of $log = 11
$ans = pow($e, $log);
$antilog = round($ans*10000)/10000;
echo "<br /> Antilog : ".$antilog;
// Calculate Log of $log = 11
$ans = log($log)/$dn;
$log = round($ans*10000)/10000;
echo "<br /> Log : ".$log;
// Calculate Antilog / Log of $log = 11
echo "<br /> Antilog / Log : ".($antilog / $log);
?>
Result:
Antilog : 59874.1416
Log : 2.3979
Antilog / Log : 24969.407231327
Hope this help you, if else please provide more details (comments) on your code.
To narrow down where your issue is coming from:
string bcdiv ( string $left_operand , string $right_operand [, int $scale ] )
bcdiv will return Division by zero only if the right operand is 0, so you can backtrace this by assuming $ac is your culprint. Try echoing $ac before the bcdiv function call to ensure it is not empty.
I'm willing to bet that this line $ac = ($ab-1); // ac = 0.9729529246182467
$ac is going negative.
You should also remove your single quotes, don't take the manual so literal. You can still pass in an int or double and the function will convert it for you. even if you cast the variable as a double.
//WITHOUT QUOTES
$ab = '1.9729529246182467';
$ac = ($ab-1);
echo bcdiv($ab, $ac, 3);
//output (2.027)
//WITH QUOTES
$ab = '1.9729529246182467';
$ac = ($ab-1);
echo bcdiv($ab, '$ac', 3);
//output Warning (2): bcdiv() [function.bcdiv]: Division by zero
This is my example array:
$arrayy[0]=48.72;
$arrayy[1]=21.32;
$arrayy[2]=48.62;
$arrayy[3]=21.31;
$arrayy[4]=48.62;
$arrayy[5]=21.31;
This function
function writeDouble($array){
for($curr = 0; $curr<count($array)-1; $curr++){
echo $array[$curr]." - ";
echo $array[$curr+1]."<br>";
$curr++;
}
}
should write a couples (0-1 , 2-3 , 4-5) - an output like:
48.72 - 21.32
48.62 - 21.31
48.62 - 21.31
What am I doing wrong, why do I got an error?
Notice: Undefined offset: 6 in C:\xampp\htdocs\xampp\lg\functions.php on line 466
Or could you define a better function to make couples? I can't think anymore... thanks
Because in the last iteration in line echo $array[$curr+1]."<br>"; you'll be looking for $array[count($array)] which is ofcource not defined!!
You're using $array[$curr + 1] but you're iterating from 0 to $curr - 1. You need an isset in case you have an odd number of values in your array.
You're incrementing 2 times (one time in your for, one time in the scope of your for).
Code solution:
$arrayy[0]=48.72;
$arrayy[1]=21.32;
$arrayy[2]=48.62;
$arrayy[3]=21.31;
$arrayy[4]=48.62;
$arrayy[5]=21.31;
function writeDouble($array) {
for ($curr = 0; $curr < (count($array) - 1); $curr += 2) {
echo $array[$curr] . " - ";
if (isset($array[$curr + 1])) {
echo $array[$curr + 1];
}
echo "<br>";
}
}
writeDouble($arrayy);
Output:
48.72 - 21.32
48.62 - 21.31
48.62 - 21.31
No more warning.
Note that you are incrementing $curr two times:
for($curr = 0; $curr<count($array)-1; $curr++){
and
$curr++
This is the reason for going out of range in your loop