Addition by ZERO - PHP - php

Could somebody please tell me why $total_value evaluates to ZERO when either $bawtry_value or $chain_value are non-zero values?
PHP
$bawtry_value = utf8_encode(money('%n', $bawtry * $price));
echo "Bawtry Value";
echo '<br />';
echo $bawtry_value;
echo '<br />';
$chain_value = utf8_encode(money('%n', $chain * $price));
echo "Chain value";
echo '<br />';
echo $chain_value;
echo '<br />';
$total_value = utf8_encode(money('%n', $bawtry_value + $chain_value));
echo "Total value";
echo '<br />';
echo $total_value;
echo '<br />';
Example Output
Result Bawtry 0
Result Chain 2
Total Pairs 2
Bawtry Value
£0.00
Chain value
£39.90
Total value
£0.00
Is there a problem with PHP adding two figures together when one is ZERO?
Any help would be great. Thanks

It seems you should change this line:
$total_value = utf8_encode(money('%n', $bawtry_value + $chain_value));
into
$total_value = utf8_encode(money('%n', $bawtry * $price + $chain * $price));
or even
$total_value = utf8_encode(money('%n', $price * ($bawtry + $chain)));
Now in calculating $total_value you have currency symbol at the beginning of $bawtry_value and $chaing_value and if you add them, they are converted to 0.
You can see this if you try to display:
echo '£0.00' + '£39.90';
first character of those strings is £ is converted to 0.
However if you try to do something like that
echo '2£0.00' + '39.90£';
result will be 41.90 because strings are converted to int until the first character that makes the string cannot be converted to int.

Related

Division with php

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);

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?
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).

unexpected result in php output with larger strings

I am trying to create a binary/hexadecimal converter to convert a denary(base 10) number/value into binary and hexadecimal.
It works fine so far for binary until the input from the form is greater than 11 digits and over(string length), ruffly as it seems to variety. after 11 digits it starts adding " - " into the outcome. Im not sure were this is coming from as I don't have an " - " in the code.
I wasn't sure if this was something to do with large integers as I saw some other questions on that topic(not in php however it was java, so not sure if there is something simpler in php)
That said I was under the impression that form inputs were always strings.
To test if a variable is a number or a numeric string (such as form input, which is always a string), you must use is_numeric(). - from : http://www.php.net/manual/en/function.is-float.php
(haven't yet got to hexadecimal but needed to mention it as some of the following code contains parts for it.)
here is the php code (note: I do check user input just not added it yet)
$inpu = $_POST['number'];
$numinput = $_POST['number'];
if (is_numeric($numinput))
{
while ($numinput >= 1)
{
$binary .= $numinput % 2;
$numinput = $numinput / 2;
}
$mult = strlen($binary) % 4;
echo gettype($numinput) . "<br />";
echo gettype($binary) . "<br />";
echo gettype($mult) . "<br />";
echo $mult . "<br />";
while ($mult < 4)
{
$binary.= "0";
$mult++;
}
$revbinary = strrev($binary);
echo $inpu . " in binary = " . $revbinary ;
echo "<br /> <br />";
echo chunk_split($revbinary, 4);
echo "<br />" . gettype($revbinary) . "<br />";
echo gettype($inpu) . "<br />";
}
else
{
if (is_numeric($numinput))
{
echo "$numinput is over the max value of 255";
}
else
{
echo "your entry is not a vaild number <br />";
echo $numinput;
}
}
Im not looking for completed version of this code as you would ruin my fun, I am just wondering why there is a "-" being entered after 11 digits or so. It also did't add the symbol before I added :
$mult = strlen($binary) % 4;
echo $mult . "<br />";
while ($mult < 4)
{
$binary.= "0";
$mult++;
}
This was to split the binary into 4s ( 0011 1101 0010 0110 ).
Edit: wondered if this would be useful:
echo gettype($numinput); result double
echo gettype($binary); result string
echo gettype($mult); result integer
gettype($revbinary); result string
echo gettype($inpu); result string
still trying to work this out myself.
Any advice is much appreciated Thanks
I would suggest simply using decbin() and dechex(). Those are functions included in php, which do exactly what you're trying to accomplish.
You might want to check if it is a number first (like you are already doing).
Then cast it to an integer (through intval()) and then apply decbin() and dechex()
http://php.net/manual/de/function.decbin.php
http://www.php.net/manual/de/function.dechex.php
http://php.net/manual/de/function.intval.php

Add 64 bit numbers in 32-bit windows

The following code:
$val = "209810563658809344";
echo sprintf('%0.0f', ($val - 1) + "<br />");
echo sprintf('%0.0f', (bcsub($val, 1)) + "<br />");
In windows 32 bit outputs:
209810563658809344
209810563658809344
How can be made the subtraction to work properly?
Both your sprint() masking and the use of + instead of . for concatenation are forcing a cast to numeric datatype
$val = "209810563658809344";
echo sprintf('%0.0f', ($val - 1)) . '<br />';
echo bcsub($val, 1) . '<br />';
Avoid the conversion to floating point and you'll be fine.
$val = "20981056365880934";
echo bcmul($val, 2, 0)." ≈ ".bcdiv($val, 2, 0)." × 2 + ".bcsub($val, 1, 0)." + 1";
Note the third scale parameter which allows you to control precision like printf(). See the bc manual

changing font makes + combine strings instead of adding values

Here is my code:
<?php
$num1 = 10;
$num2 = 15;
echo "<font color='red'>$num1 + $num2</font>" . "<br>";
?>
I expect it to equal "25", when I add a font color it equals "10 + 15". Why?
You cannot do math inside a string. Instead, close the string. perform your addition operation, and concatenate the result.
echo "<font color='red'>" . ($num1 + $num2) . "</font><br>";
As Orangepill wisely points out, this can be accomplished more efficiently like this:
echo "<font color='red'>",($num1 + $num2),"</font><br>";
change
echo "<font color='red'>$num1 + $num2</font>" . "<br>";
to
echo "<font color='red'>",($num1 + $num2),"</font><br>";
You need to concatenate your string otherwise math will not work
echo "<font color='red'>".($num1 + $num2)."</font>" . "<br>";

Categories