php function to check if number is divisible by 0 - php

I have checked a bunch of posts on stackoverflow and on articles on google but none of them were able to answer my question. Here is my code (i've simplified it instead of posting my code)
$first = 10;
$second = 0; //comes from db row count
$total = !is_int($first/$second) ? 0 : $first/$second;
problem is when i do this I keep getting the Division by zero error. I have a bunch and $second isnt always 0, it can be any number. But it does come out to 0 since the row counts for whatever query it comes out as 0. Is there a safe way of checking to see if $first can be divided by $second without giving an error? I have tried # before the !is_int and that just breaks all other statements.

Try this:
$total = ($second == 0) ? 0 : $first / $second;

You can't divide by 0 it is undefined. If you want to handle division by 0 just check if the divisor isn't equals to 0. Or a safer way, chack if it is a positive integer:
$first = 10;
$dbRowCount = dbFunction();
if ($dbRowCount > 0) {
$total = $first / $dbRowCount;
} else {
//Error handling
}

The ternary structure can accept more than one condition. and it will work just as any other if condition, and won't try the second condition if the first fails.
So, just add it
$total = ($first!==0 && $second!==0 && !is_int($first/$second)) ? 0 : $first/$second;

You might want to try checking if your $Second variable is 0.
Something like:
$First = 10;
$Second = $row['table_column'];
if ($Second == 0) {
echo "Oops this will be an error";
}
else
$First/$second = $me;

Related

My while loop hits the maximum execution time with no specific, meaningful errors given

Good afternoon, good people of SO!
I'm trying to make a binary calculator, which adds two binary strings together and returns the result in binary.
However, my loop (used for checking the input consists of 0 or 1) seems to falter and return either a 503 (Service Temporarily Unavilable) or suggests I've hit the maximum execution time (30 secs).
I can't figure out why. It seems to bypass this problem if I change && to ||, however this returns a false positive for a bad input.
Here is the code:
// Spring cleaning - add some variables
$submit = htmlspecialchars(strip_tags(stripslashes($_POST['submit'])));
$val1 = htmlspecialchars(strip_tags(stripslashes($_POST['val1'])));
$val2 = htmlspecialchars(strip_tags(stripslashes($_POST['val2'])));
$val1_length = strlen($val1);
$val2_length = strlen($val1);
$val1 = str_split($val1, 1);
$val2 = str_split($val2, 1);
// Val 1 - Checking
$count = 0; // count variable counts how many times the loop recurs and stops it appropriately
while ($count <= $val1_length) {
if(($val1[$count] != 0) || ($val1[$count] != 1)) { // checks if input is comprised of 0 or 1
showInputError();
exit(); // input does not contain 0 or 1, abort script and do not attempt further calculations
$count = $count + 1; // increment the count variable after one successful loop
}
} // Val1 was fine
Thanks in advance! :)
As bwoebi said in the comments, put the bracket one line higher in the if statement, as you're not actually counting up, so the loop will go on forever if no value is found..
$count = 0; // count variable counts how many times the loop recurs and stops it appropriately
while ($count <= $val1_length) {
if(($val1[$count] != 0) || ($val1[$count] != 1)) { // checks if input is comprised of 0 or 1
showInputError();
exit(); // input does not contain 0 or 1, abort script and do not attempt further calculations
}
$count = $count + 1; // increment the count variable after one successful loop
} // Val1 was fine
Why don't you simply use a simple regex like
$input= '1101010001010101110101';
preg_match('/^[01]+$/', $input);
It seems to me you are not verifying your $val1_length in the while loop. What happens if your POST values are empty? You will get an infinite loop, so you might want to replace the while like this:
while ($count <= $val1_length && !empty($val1_length) {...}

Shorthand to set var = whichever is greater of 2 variables

I have 2 different possible values I use in an equation. I want to select whichever one exists and is greater using the least amount of code. It's possible neither variable exists, in which case year = 0, but one or both might exist. I.e:
if(isset($this->average['year'] || isset($this->Listings['year']) {
$year = whichever is greater of the above.
} else {
$year = 0;
}
It seems like there must be a shorter/ less messy way to do this than:
if (isset($this->average['year']) && ($this->average['year'] > $this->Listings['year']) {
$year = $this->average['year'];
} elseif( isset($this->Listings['year'])) {
$year = $this->Listings['year'];
} else {
$year = 0;
}
Thanks
Using max and the ternary operator to do isset checks on both variables you can shorten it to this:
$year = max(array(
isset($this->average['year']) ? $this->average['year'] : 0,
isset($this->Listings['year']) ? $this->Listings['year'] : 0
));

Can you help me get this PHP explode/array/numrows/etc block working?

Ok, so here's my code:
if ($_GET['send'] === "yes") {
$name = $_POST['msg-to'].", ";
$nameParts = explode(", ", $name);
$recipients = array();
for ($x = 0; $x >= 10; $x++) {
$name_query = mysql_query("SELECT * FROM users WHERE username='".$nameParts[$x]."'");
while($value = mysql_fetch_array($name_query)){ $name_numrows = mysql_num_rows($name_query); }
if ($name_numrows = 1) {
$recipients[$x] = $nameParts[$x];
$msgError .= '<span class="success">'.$nameParts[$x].' is a valid user.</span><br>';
} else {
$msgError .= '<span class="warning">'.$nameParts[$x].' is not a valid user, message did not send.</span><br>';
break;
}
}
}
But when a user enters a username for this message to be sent to, it doesn't seem to work AT ALL. It doesn't echo either of the two error messages, and doesn't return an error. It doesn't do anything.
Any feedback at all would be absolutely wonderful :D
I tried to help in the comments above but I think a more clear explanation is needed so I'm resorting to posting an answers. Your code:
for ($x = 0; $x >= 10; $x++) {
This code block declares $x = 0 as the first part of the statement, this is the initialisation.
The second part $x >= 10 is the condition. It states that while $x is greater than or equal to 10 you want to execute an iteration of the loop.
The final part $x++ is the afterthought. It states that on each successful iteration of the loop you want to increment the value of $x.
Because you initialise $x to be 0 and then set the condition that it has to be greater than or equal to 10 >= 10 the condition will fail first time, every time. 0 can't be great than or equal to 10. I imagine what you probably want for your condition is something like while $x is less than or equal to 10 $x <= 10.

if number is a decimal between 2 numbers (php)

I'm writings a PHP script that calculates an average of a number.
EXAMPLE:
$rating = 7;
$votes = 3;
$AvgRating = number_format($rating / $votes,1);
The return $AvgRating for this would be 2.3 (to 1 decimal place).
is it possible to say.....
if ($AvgRating > 2 && $AvgRating < 3){
$display = 'between';
}
echo $display;
I have tried but it does not work, I have tried google but don't know exactly what I need to look for.
This code evaluates correctly...
<?php
$rating = 7;
$votes = 3;
$AvgRating = number_format($rating / $votes,1);
if ($AvgRating > 2 && $AvgRating < 3){
$display = 'between';
}
echo $display;
?>
Hi there is some mistakes $AvgRating retunrs 2.3 not 7.3
So you have to check with this
$rating =7; $votes=3;
$AvgRating = number_format($rating / $votes,1);
if ($AvgRating > 2 && $AvgRating < 3.0){
echo $AvgRating;
}
If your question is whether the condition inside the if statement is correct, yes it is.
However in your case, the if condition fails since the value of $AvgRating (7/3) is less than 7. So you probably might be checking whether $AvgRating is greater than 2.

While Loops and Multiple Conditions

Is it possible to write multiple conditions in a while loop? If not, what is an alternative? I tried it and was returned with an error relating the line of code that sets up the conditions for the while loop. Here is an example of what I mean.
$s = 1;
while ($result_row = mysql_fetch_assoc($query) && $s < 5)
{
echo $result_row['id'];
$s++;
}
That is possible, but because = has lower precedence than && you need parentheses to ensure that your statement is interpreted correctly:
while (($result_row = mysql_fetch_assoc($query)) && ($s < 5))
The parentheses around $s < 5 are not required here, but I've included them for clarity.
However it would be easier just to modify your query to only return 5 rows, by adding LIMIT 5.
SELECT ...
FROM yourtable
ORDER BY ...
LIMIT 5
You could try:
$s=1
while ($result_row = mysql_fetch_assoc($query))
{
echo $result_row['id'];
$s++;
if($s>5){
break;
}
}
http://php.net/manual/en/control-structures.break.php
while i see nothing wrong in that. the other way round is to do something like this.
$s = 1;
while ($result_row = mysql_fetch_assoc($query))
{
if($s < 5) {
//enter the condition
}
$s++;
}
The value of $result_row is probably being set to the Boolean condition of whether mysql_fetch_assoc($query) returns something true-ish and $s is less than 5. So trying to read $result_row as a dictionary no longer works.
You can use parenthesis to specify exactly how things get parsed:
while (($result_row = mysql_fetch_assoc($query)) && ($s < 5))
This way, $result_row gets set to mysql_fetch_assoc($query), which is what you want, and the loop continues as long as the logical value of that assignment returns something true-ish, as well as s is less than 5.

Categories