Warning: Division by zero in ... on line 133 - php

Basically, i've made a script that login to a website, get elements from the website, and divide one element with another. The problem is, i have already checked plenty of times, and the divisor is NOT zero. here is the snippet:
if($num==0)
{
echo "<td>".$estate_income."/".$num."</td>";
}
else
{
echo "<td>".$estate_income/$num."</td>";
}
this would output something like 50/2000, which means the if statement is true, which means that $num is somehow equal to 0. if i try to divide the two variables with each other, it would output php warning diivision by zero:
echo "<td>".$estate_income/$num."</td>";
What i ask now is, for a solution, maybe some error detection methods that could tell me what i am doing wrong. it's probably something very obvious that i have overlooked.
Thanks in advance!
Ahmad Albayati
Edit:
try
{
echo "<td>".$estate_income/$num."</td>";
}
catch(Exception $e)
{
echo 'Caught exception: ', $e->getMessage(), "\n";
}
Outputs Warning: Division by zero in . . . on line 133
The variables i am trying to divide is within a foreach loop.
The $num variable is defined in a function that gets included:
function num_format($n)
{
$n=str_replace(",","",str_replace(" ","",$n));
if(strpos($n,".")===FALSE)
{
if(strpos($n,"K")!==FALSE)
{
$n=str_replace("$","",str_replace("K","000",$n));
}
elseif(strpos($n,"mil")!==FALSE)
{
$n=str_replace("$","",str_replace("mil","000000",$n));
}
elseif(strpos($n,"bil")!==FALSE)
{
$n=str_replace("$","",str_replace("bil","000000000",$n));
}
elseif(strpos($n,"tril")!==FALSE)
{
$n=str_replace("$","",str_replace("tril","000000000000",$n));
}
else
{
$n=str_replace("$","",$n);
}
}
else
{
$n=str_replace(".","",$n);
if(strpos($n,"K")!==FALSE)
{
$n=str_replace("$","",str_replace("K","00",$n));
}
elseif(strpos($n,"mil")!==FALSE)
{
$n=str_replace("$","",str_replace("mil","00000",$n));
}
elseif(strpos($n,"bil")!==FALSE)
{
$n=str_replace("$","",str_replace("bil","00000000",$n));
}
elseif(strpos($n,"tril")!==FALSE)
{
$n=str_replace("$","",str_replace("tril","00000000000",$n));
}
else
{
$n=str_replace("$","",$n);
}
}
global $num;
$num=$n;
}

Found the problem. As I have already mentioned, I got the values from a website. When I use var_dumb on the string, it outputs string(149) "202000". This actually had confused me, because the string/number was only 6 characters. so I decided to look at the source code, and I found this:
<spanstyle="white-space:nowrap;"><imgsrc="http: staticstorm8com="" vl="" images="" bloodpng?v="330"width="9"height="12"style="padding-right:2px"">202000<br></imgsrc="http:></spanstyle="white-space:nowrap;">
I got some other HTML elements in my variable when I was taking the values from the website.

Related

Creating a simple php page that allows the user to input characters to search for names

I am trying to make a php page where we can input characters and select year of birth
After submitting it should show all the corresponding name but it doesn't work.
For example I input 'a' and the name containing 'a' having the same year as selected should appear.
This is my code:
In data.php I have like this
$person[0]=array('name'=>'Daniel','dateofbirth'=>2000);
$person[1]=array('name'=>'Gaetan','dateofbirth'=>1980);
My function.php
<?php
function comparator($word,$dateofbirth) {
include("data.php");
$p=1;
for($i=0;$i<count($person);$i++) {
$position=strpos(strtolower($person[$i]['name']),$word);
if($position === false) {
$p++;
}
else {
if($dateofbirth==$person[$i]['dateofbirth']) {
echo $person[$i]['name'] ;?><br /><?php
}
}
}
if($p==count($person)) {
echo "No results found";
}
}
?>
And the index.php, I used get method
I think my function.php is the problem but I don't know how to fix it.
I think this should solve your problem - https://3v4l.org/oQ1BC - however I feel it's necessary to say that it's inefficient and in production data are never stored that way, you should store the details of people in a database and connect to it and perform an SQL query. This only answers the original question.
function findPeople($searchString, $YoB, $listOfPeople){
$peopleFound = [];
foreach($listOfPeople as $individual){
if(strpos($individual['name'], $searchString) !== false && $individual['dateofbirth'] == $YoB){
$peopleFound[] = $individual;
}
}
return $peopleFound;
}
$listOfPeople = array();
$listOfPeople[0]=array('name'=>'Daniel','dateofbirth'=>2000);
$listOfPeople[1]=array('name'=>'Gaetan','dateofbirth'=>1980);
print_r(findPeople('a', 2000, $listOfPeople));

get rid of error before results show up with php

the below script throws an error before the results the script executed. Though i get the results i want but i want to get rid of the error that throws up.
When the results equals to 1 the error doesn't show up, but when its more than 1 the error comes.
Notice: Trying to get property of non-object in
C:\xampp\htdocs\server_scripts\complains_list.php on line 1
if(count($customers->User_Name)=='1') {
echo json_encode(array($data));
}else
{
echo json_encode($data);
}
You just need to check that variable is set or not, check manual
if(isset($customers->User_Name) && count($customers->User_Name)=='1')
{
echo json_encode(array($data));
}
else
{
echo json_encode($data);
}
I guess that at some point your $customer isn't instantiated. Thus you have to test for its existence :
if($customer != null && count($customers->User_Name)=='1') {
echo json_encode(array($data));
} else {
echo json_encode($data);
}

Laravel: recursive function not working as expected. It is returning value from wrong iteration [duplicate]

This question already has answers here:
How to use return inside a recursive function in PHP
(4 answers)
Closed 9 months ago.
I am trying to calculate parent names of a person recursively to a specific person ID. I've written recursive call for this but it is behaving weirdly. I've tried to debug it but still don't get what I am doing wrong with it.
Here is my script:
public function full_name_to_root()
{
$name = $this->name;
// printf('caller');
$full_name = FamilyTree::getNameToRoot($this,$name,1);
dd($full_name);
return $full_name;
}
public static function getNameToRoot($daleel,$name,$c)
{
$halt = false;
$c+=1;
echo 'in rec. <br>';
$parent = $daleel->parent;
if(!$parent){
$halt = true;
return $c;
}elseif ($parent && $parent->family_tree_id==6) {
echo 'Reached to where we want to stop <br>';
$name .= ' '.$parent->name;
$halt = true;
return $c; // As you can see in output when control reaches it is not stopping the execution, but it is always going to end
}elseif($parent){
echo 'call again <br>';
$name .= ' '.$parent->name;
$halt = false;
FamilyTree::getNameToRoot($parent,$name,$c);
}
// Control should never reach here but it is coming here every time and more annoying thing is that it is printing highest count(or in case of name the most large, which also the required one) at first time and then gradually prints lower
echo "<br>";
echo $c;
echo "<br>";
// function executes above echo statements 6-7 times but only executes the return statement last time.
return $c; // I am sending count in response for just testing purpose. It is behaving same as $name is behaving.
}
I have adding some flags for debugging purpose here is the output of this function.
Any help sorting out this issue would be amazing. Thanks!
To give you are starting point I would say, that your main problem is caused when you enter this if branch.
elseif($parent){
echo 'call again <br>';
$name .= ' '.$parent->name;
$halt = false;
FamilyTree::getNameToRoot($parent,$name,$c);
}
You don't have a return statement at FamilyTree::getNameToRoot(...)
So the the method does not return and continues to run after the subsequent calls to FamilyTree::getNameToRoot() are finished.
So just use
return FamilyTree::getNameToRoot($parent,$name,$c);
The $halt variable is not needed at all.
Yes, it will always continue because you are not stopping it. You have to manually stop with something like this :
....
$halt = false;
while ( !$halt )
{
echo 'in rec. <br>';
$parent = $daleel->parent;
...
elseif($parent){
echo 'call again <br>';
$name .= ' '.$parent->name;
$halt = false;
FamilyTree::getNameToRoot($parent,$name,$c);
}
}
You may have to rearrange a few things inside the while loop but at least it will stop running as soon as $halt is true.
Try this, if it does not work, I may have missed something.
Good luck mate!

PHP getopt with if() elseif() break the middle condition

I am not sure what is going wrong, nor from the official documentation I can get much help.
But this is what is happening.
I have option 'a', 'c:' and 'm:' to read from the command line using getOpt()
They are laid out as:
if ($op = getopt("a")) {
doAll();
} elseif ($op = getopt("c:")) {
doSome($op["c"]);
} elseif ($op = getopt("m:")) {
doOne($op["m"]);
} else {
echo "INVALID ARGS"; exit;
}
The option 'a' and 'm' works find but when I use option 'c' with:
php4 rebuild_mastertag.php -c 1234
It always prints INVALID ARGS
To make things more mysterious if I pass 1 or 12 or 12345678 it works but it doesn't for 123, 1234, 12345, 123456, 1234567 sort of numbers.
Really baffled.
Thank you for for your time.
Thanks #hchr
Your solution seems to work without trouble:
$op = getopt("ac:m:");
if (empty($op)) {
alertForInvalidArgument();
} else {
callProcessor($op);
}
function callProcessor($op)
{
if ($op["a"]) {
doAll();
} elseif ($op["c"]) {
doSome($op["c"]);
} else {
doOne($op["m"]);
}
}

Calculate number of squares from a rectangle

I'm working on some PHP code but I'm stuck with a logic.
I need to find out the number of squares from a rectangle.
I'm unable to implement this in PHP.
Please help.
I tried this:
function getcount($length,$breadth,$count=0){
$min=min($length,$breadth);
if($length>$breadth){
$length=$length-$min;
$count++;
return getcount($length,$breadth,$count);
}
else if($breadth>$length){
$breadth=$breadth-$min;
$count++;
return getcount($length,$breadth,$count);
}
else{
$count+=($length/$min);
}
return $count;
}
But some how it doesn't pass all the use cases.
And i do not know on which use cases, it fails?
I think the easiest way to calculate the number of squares in a rectangle is to substract the found squares from it while it disappears completely.
It works fine for me:
function getcount($width,$height) {
$total=0;
while($width && $height)
{
if($width>$height)
{
$width-=$height;
}
else if($height>$width)
{
$height-=$width;
}
else
{
$width=0;
$height=0;
}
$total+=1;
}
return $total;
}
echo getcount(5,3)."<br/>";
echo getcount(5,5)."<br/>";
echo getcount(11,5)."<br/>";
Output:
4
1
7
In my opinion there is nothing wrong in your code. The output from the code in OP is exactly the same as the output of the code in the accepted answer. You can run this (where getcount() is the function from OP and getcount2() is the function from the Balázs Varga's answer):
for ($i=0; $i<10000; $i++)
{
$a=mt_rand(1,50);
$b=mt_rand(1,50);
$r1 = getcount($a, $b);
$r2 = getcount2($b, $b);
if ($r1 != $r2)
{
echo "D'oh!";
}
}
and it will not return anything at all.
The only flaw is your code will throw a warning message when you run getcount(0, 0).
Also, the second line in your code ($min=min($length,$breadth);) is a bit redundant. You can write the same this way:
function getcount($length,$breadth,$count=0){
if($length>$breadth){
$length=$length-$breadth;
$count++;
return getcount($length,$breadth,$count);
}
else if($breadth>$length){
$breadth=$breadth-$length;
$count++;
return getcount($length,$breadth,$count);
}
else if ($breadth!=0){
$count++; // there is no need to divide two same numbers, right?
}
return $count;
}

Categories