PHP Division By Zero? [closed] - php

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Two hours ago the following script worked. Now for some reason, I'm getting an error "Warning: Division by zero in _ on line 30". Here's the script. Can anyone tell me what I'm doing wrong and how to correct it?
Basically this script is pulling data from two elements on another website, dividing them to get a number which in turn is being used to set the width of an element. Been troubleshooting this for a while. Thanks so much in advance!
<?php
define("FFF_SIXDEGREES", "http://www.stayclassy.org/fundraise?fcid=257739");
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, FFF_SIXDEGREES);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
if(!($results = curl_exec($curl))) {
print("{ \"total\": \"$0.00\" }");
return;
}
$pattern = '/<li class="goalTitle">Raised so far:<\/li>\s*<li>\$([\d\.,]+)<\/li>/';
preg_match($pattern, $results, $matches);
$total = $matches[1];
$total = str_replace(",", "", $total);
// printf("<h2 class=\"raised-total\">$%s</h2>", formatMoney($total, true));
$pattern2 = '/<li class="goalTitle">My goal:<\/li>\s*<li>\$([\d\.,]+)<\/li>/';
preg_match($pattern2, $results, $matches);
$total2 = $matches[1];
$total2 = str_replace(",", "", $total2);
// printf("<h2 class=\"goal-total\">$%s</h2>", formatMoney($total2, true));
$diff = ($total/$total2) * 100; // THIS IS THE LINE OF CODE IN QUESTION
function formatMoney($number, $fractional=false)
{
if ($fractional) {
$number = sprintf('%.2f', $number);
}
while (true) {
$replaced = preg_replace('/(-?\d+)(\d\d\d)/', '$1,$2', $number);
if ($replaced != $number) {
$number = $replaced;
} else {
break;
}
}
return $number;
}
echo "<div class=\"progress-header\" style=\"width:$diff%;\"><span class=\"raised-amount\">$$total</span><span class=\"goal-amount\">$$total2</span></div>";
?>

The error message is helpfull here. On that line:
$diff = ($total/$total2) * 100;
the $total2 variable maybe sometime equal to 0, so php cannot execute the calculation (it's impossible to divide by zero). So you chould do somthing like this :
if($total2) // This condition will be true if $total2 != 0
$diff = ($total/$total2) * 100;
else
$diff = 0;
Also, I can see on your code that $total and $total2 are string, converted into float. This can be a source of error too. You should force the conversion to float using floatval :
if(floatval($total2))
$diff = ( floatval($total) / floatval($total2) ) * 100;
else
$diff = 0;

$total2 is 0 because you set wrong RegExp.
First, add i after last / in both patterns to change mode to case insensitive (you've got eg. Raised So Far on website but you're using Raised so far). Next, check what are you getting in your both $matches.

Given that it is actually only a warning and doesn't cause the script to stop, you can also use the following to simply hush the messages on that line:
<?php
$var=4;
$diff = (100/$var) * 100;
echo $diff."<br><br>";
$var=0;
$diff = (100/$var) * 100;
echo $diff."<br><br>";
$var=0;
$diff = #(100/$var) * 100; // Note the # symbol before the possible wanring
echo $diff."<br><br>";
?>
Output:
2500
Warning: Division by zero in C:\Server\www\test1.php on line 8
0
0
Basically, it will render as a zero. It's not the best way, but in terms of efficiency, if you are dealing with a lot of data, it might be better to not display the warning as compared to performing validation on each row of data.
It's probably not what I would do (though I have done it once) but I thought I would offer it as a suggestion.

Related

PHP code is returning "x=NAN" [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
My code is:
$a = $_GET["valA"];
$b = $_GET["valB"];
$c = $_GET["valC"];
$d = pow($b,2) - 4 * $a * $c;
$e = sqrt($d);
$f = $e - $b;
$g = 2 * $a;
$h = $f / $g;
echo "x = $h";
And it is returning:
x = NAN
Please point out my mistake.
Issue is with $e = sqrt($d);
Whenever $d gives a NEGATIVE value sqrt($d) returns NAN.
EXAMPLE
echo $e = sqrt(-4);
returns NAN
AND
echo $e = sqrt(4);
returns 2
NAN simply means Not A Number. The values you are pulling from the URL may be strings, which would cause this issue.
Also I think the problem may occur if you are taking the square root of a negative number.
You could use something like this to solve it
<?php
$a = 10;
$b = 20;
$c = 30;
$d = pow($b,2) - 4 * $a * $c;
if($d < 0){
$d *= -1;
}
$e = sqrt($d);
$f = $e - $b;
$g = 2 * $a;
$h = $f / $g;
?>

PHP procedure for returning a random number in the range 65, 66, ..., 90, 97, 98, ..., 122 [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
My web hosting service doesn't have a debugger, so I don't have any insight into why my procedure is failing. I made the following function to generate a random string of length n, and tried to optimize it as much as possible. Any idea what's wrong and how I could possibly make it more elegant? I just started learning PHP, so it's possible I've expected some syntax from other languages to transfer to PHP when in fact they don't.
function rand_str(int $n)
{
$str = "";
for (;$n > 0; --$n)
{
/* ASCII vals are 'A'=65, 'B'=66, ..., 'Z'=90, 'a'=97, 'b'=98, ..., 'c'=122 */
int $val = rand(0,51);
$str += (char)($val < 26 ? $val + 65 : $val % 26 + 97);
}
return $str;
}
A working version of your code:
function rand_str($n)
{
$str = "";
while($n-- > 0)
{
/* ASCII vals are 'A'=65, 'B'=66, ..., 'Z'=90, 'a'=97, 'b'=98, ..., 'c'=122 */
$val = rand(0,51);
$str .= chr($val < 26 ? $val + 65 : $val % 26 + 97);
}
return $str;
}
If you're only going to use two parts of the for loop, you may as well use a while. Strings are concatenated using .=, not +=. You don't specify types in PHP. The function chr returns a character from an ascii code.
This seems like quite a brute-force way of learning a new language. It's not a very good idea to just assume how things are going to work!
As an aside, even if you don't have access to your server configuration, you can enable warnings by adding these lines to the top of your script:
error_reporting(E_ALL);
ini_set("display_errors", 1);
This should help you with debugging.
This code works and it's more flexible I think.
function rand_str(int $n)
{
for ($str = "", $n>0; --$n)
{
$val = rand(0,1) ? rand(ord("A"),ord("Z")) : rand(ord("a"),ord("z"));
$str .= chr ($val);
}
return $str;
}
function rand_str($n)
{
$str = "";
for (;$n > 0; --$n)
{
$val = rand(0,51);
$str .= ($val < 26) ? $val + 65 : $val % 26 + 97; //Here you have to concatenate with a '.'
}
return $str;
}

PHP function to get N random values (as array) which's sum result in X [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I think the subject hits it better than I was expecting.
I need a function which returns random numbers which result in a given value (X) when they are summed up.
Something like this:
getRandomTo(10); // result for example: array(2,3,5)
getRandomTo(10); // result for example: array(4,3,3)
getRandomTo(12); // result for example: array(5,1,6)
I could not find a generic algorithm function for solving that requirement. Further more I cannot imagine a FAST and performant way to create something like this my self.
Please help me out
function getRandomTo($num)
{
$x = Array();
$i = 0;
do
{
$x[$i] = rand(1,$num);
$num = $num - $x[$i];
$i++;
}while($num > 0);
print_r($x);
}
Maybe do this:
create a random value between 0 and X; say this one is called r1. save this in your array.
create another random value between 0 and (X-r1), name it r2. save it also.
do these steps as often as you need it (or as long as r1+...+rn is lower than X)
Another solution:
function randomTo($numIn) {
$numOut = 0;
$numbers = array();
do {
$add = rand(1, $numIn);
if($numOut + $add > $numIn)
continue;
$numOut += $add;
$numbers[] = $add;
} while( $numOut != $numIn );
return $numbers;
}
$result = randomTo(15);
var_dump($result);

Mathematical operation of CHARACTER [not numeric] in php [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
is there any way to sum/substrate character in php?
For example if
$var1 = 'a';
$var2 = 'b';
$var3 = 'a';
$calculation = $var1 - $var2 + $var3;
echo $calculation;
I want the output as 2a-b
Just like we did in high school algebra?
I wrote a simple function to make something like what you want.
It's just an example, you will have to improve it a lot if you really want to use it, but is a good start.
Limitations:
Only works with letters (Won't work propely if you add numbers, you will have to add that functionaliy).
ALL the letters must have their plus or minus.
You must use spaces before a plus or minus.
This is definitely not the best way to do it, as I said you have to improve it. I wrote it fast but I tested it a bit.
<?
function calc($str){
$data = preg_split("/ /", $str);
$used = Array();
$buffer = "";
foreach ($data as $pos=>$letter){
foreach ($data as $pos2=>$letter2){
if ($letter[1] == $letter2[1] && !in_array($pos, $used) && !in_array($pos2, $used) && $pos != $pos2){
$first = $letter[0] == '+' ? 1 : -1;
$second = $letter2[0] == '+' ? 1 : -1;
$buffer .= ($first+$second).$letter[1];
$used[count($used)] = $pos;
$used[count($used)] = $pos2;
}
}
}
foreach ($data as $pos=>$letter){
if (!in_array($pos, $used)){
$buffer .= $letter;
}
}
return $buffer;
}
echo calc("+a -b +a");
?>
Output:
2a-b

Find first zero bit [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
What's the easiest way to find the first zero bit with PHP?
For example, say I have an integer 47 which is 111101, how can I find out that the 5th bit is the first unset bit? This needs to work to cater for different integers.
$value = 47;
$i = $j = 1;
while (true) {
if (($value & $j) == 0) {
break;
}
$j = $j << 1;
$i++;
}
echo "bit $i is 0";
If you want to eliminate the use of $i as a counter, you can do a little bit of extra math:
$value = 47;
$j = 1;
while (true) {
if (($value & $j) == 0) {
break;
}
$j = $j << 1;
}
echo "bit ", (log($j) / log(2) + 1), " is 0", PHP_EOL;
The +1 is necessary because you're starting your binary as bit 1 rather than as bit 0
Use decbin to return a string of 0 and 1.
Then, use strpos to find the first 0 caracters.
$str = decbin(47);
$result = strpos($str, '0');

Categories