if ($unitWeight != 0)
{
$saleableUnits = ($sumQty/$unitWeight);
$unitCost = ($sumCost/$saleableUnits);
}
I'm expecting this statement to run only if $unitWeight is greater than 0. It seems to run no matter what and I get this error.
"Warning: Division by zero in"
Try typecasting the your variable
$unitWeight = (int) "0";
var_dump(($unitWeight));
Or use abs() or intval()
$unitWeight = "0";
var_dump(abs($unitWeight));
Use greater than ( > )
if ($unitWeight > 0)
{
$saleableUnits = ($sumQty/$unitWeight);
$unitCost = ($sumCost/$saleableUnits);
}
Use method empty() for checking code like this because empty() also check is the $unitWeight are set somewhere
if ( !empty($unitWeight) ){ $saleableUnits = ($sumQty/$unitWeight); $unitCost = ($sumCost/$saleableUnits);}
If you want the statement to run only if $unitWeight is > 0, then that is what you should use.
See below:
if (intval($unitWeight) > 0){
$saleableUnits = ($sumQty/$unitWeight);
$unitCost = ($sumCost/$saleableUnits);
}
Use intval() to get intval — Get the integer value of a variable as described in the official documentation here
Please keep in mind, it is always beneficial and imperative that you sanitize your input and ensure that only numeric values are accepted.
As the previous answer try using
if ($unitWeight > 0){
$saleableUnits = ($sumQty/$unitWeight);
$unitCost = ($sumCost/$saleableUnits);
}
And the big thing is may be already the $unitWeight must be greater than 0 i think, that's why it is always going inside the if condition.
before the if condition try printing the value of $unitWeight variable, so that you can find what is inside the variable and also the reason why it gets inside the condition.
Then finally like same print the variables $sumQty and $sumCost.
might be any of these variable have a value of 0 that is why it is showing the error you have mentioned
Related
I'm currently building a room booking system and was wondering how to check if the user has correctly entered an integer i.e. 0,1,2,3,4,5 on the form and not anything else (i.e. left it blank, entered decimal number or alphabet).
$capacity = $_GET["capacity"];
Thanks in advance!
As per comments check the post variable is set first, else a warning is raised in recent PHP versions:
isset($_GET['capacity'])
Hence, you can:
Cast it to an int:
$capacity = isset($_GET['capacity']) ? (int)$_GET['capacity'] : null
Use a function:
$capacity = is_numeric($_GET['capacity']) ? (int)$_GET['capacity'] : null;
// cast to int as is_numeric will return floats too
Make it a number and compare against original input:
$capacity = ((int)$_GET['capacity']) == $_GET['capacity']) ? $_GET['capacity'] : null;
This last is ideal in situations where the input might exceed MAX_INT or be altered by casting in some other way.
preg_match('/^[0-5]$/', $_GET['capacity']);
If not just limited from 0 to 5,
preg_match('/^[0-9]+$/', $_GET['capacity']);
this is a filtering job, so a good option is to use the filter module (http://php.net/filter)
so you might use filter_var or filter_input with FILTER_VALIDATE_INT as a flag and compare the result to false (strict comparison, to avoid confusion caused by 0)
I have a different approach if you like:
$validValues=array('0','1','2','3','4','5');
$capacity = $_GET["capacity"];
$isValid=in_array($capacity,$validValues); //TRUE if entered value is in the valid values.
Values read from the $_GET are strings anyway.
PHP manual: in_array()
Check out is_numeric function.
Use regular expression to match for a whole number
preg_match('/^[0-9]\d*$/', $variable)
if($_GET["capacity"] >= 0 && $_GET["capacity"] < 5)
{
//prefect
}
else
{
//invalid
}
echo "<h2 style='margin:0; padding:0;'>Recent Comments</h2>";
if ($sth7->rowCount()) {
while($row7 = $sth7->fetch(PDO::FETCH_ASSOC)) {
echo "<div class='comment'>{$row7['usr']} said";
}
}
else($sth7->rowCount() = 0)
echo "User";
Can't use method return value in write context
Why doesnt that rowcount() = 0 logic work?
= is the assignment operator in PHP.
You're basically trying to assign 0 to $sth7->rowCount().
Perhaps you mean $sth7->rowCount() == 0?
Also, you really don't need the if else if. It could be just an if else:
if($sth7->rowCount()) {
} else {
}
rowCount() returns an integer, and any integer except for 0 will cast to true.
Try rowcount() == 0 to compare with 0, your code (rowcount() = 0) tries to assign 0. Also, it's may be useful to put constant on the left side while comparing : (0 == rowcount()) to make such errors easier to detect.
else doesn't take any logic, it just runs if it's assosciated if (and any elseifs) didn't evaluate true.
Also, = is an assignment operator - read it as "becomes equal to"
$var = 1; // Var becomes equal to 1
== is an equality operator, it tests if two expressions are equal
$var == 1 // Var is equal to 1
You probably want
else if ($sth7->rowCount() == 0)
echo "User";
I am doing this check on a variable:
if (empty($num) || !isset ($num) || !is_numeric ($num))
{
$population = -1;
}
else
{
$population = $num;
}
And what I was hoping for is that if num is null or not a number or doesn't exist, to make $population = -1 and in all other cases to give $population the value of $num
But that is not happening for me. Any ideas why this isn't working the way I thought it would?
Is this possibly an issue with scoping?
<?php
$num=23;
tryStuff();
function tryStuff(){
global $num; //if this line is commented out, then -1 is printed.
if (empty($num) || !isset ($num) || !is_numeric ($num))
{
$population = -1;
}
else
{
$population = $num;
}
echo "$population<br>";
}
?>
is_numeric should work good by itself. If instead of $num the value was a super global, using isset would be a good idea to avoid warnings:
$population = is_numeric ($num) ? $num : -1;
// or
$population = isset($_GET['num']) && is_numeric($_GET['num']) ? $num : -1;
post an example of $num
using regex:
$population = preg_match("/^\d+$/", $num) ? $num : -1;
I'm going to go out on a limb here and say that you're inputting the number 0 and getting unexpected results, because empty(0) is true.
I think if you change your code to:
if (!isset ($num) || !is_numeric ($num))
{
$population = -1;
}
else
{
$population = $num;
}
You will get the desired results.
EDIT Possibly you are looking for an Integer or a Float in which case you should replace is_numeric with is_int or is_float respectively.
Why not flip it around and go with a positive as a primary check?
$population = (isset($num) && is_numeric($num)) ? $num : -1;
I've never had fun with negative's and "or" statements :)
What happens if you var_dump($num);?
Personally, my guess is that PHP is interpreting something input as a number, when you are expecting it to be a string. Such examples might include things which might accidentally convert, like '0xFF' (a string of the Hex for 255).
Clearly the issue is not about isset, because if it were, you would have caught it, and you said to evolve that this happens even without empty. This means that something which you are expecting to be is_numeric($num) === FALSE can be evaluated as TRUE.
I am trying to get this:
if($a[2] > $b[2] && $c[2] < 3) echo "bingo";
But because the condition is retrieved from database, I need to get the whole condition into a variable and then somehow find a way to change the variable back into a condition. I thought it will be something along this line:
$condition = "$a[2] > $b[2] && $c[2] < 3";
$evaledCondition = eval("$condition;");
if($evaledCondition) echo "bingo";
Apparently it didn't work. Am I missing something?
eval() returns NULL unless return is
called in the evaluated code
$evaledCondition = eval("return $condition;");
I have an IF statement that consists of two separate function calls
passing values to two variables. Obviously if neither value is 'FALSE'
then the code block is executed:
<?php
class MyValidater {
static function validateString($string) {
if (preg_match("/[A-Za-z]+/", $string)) {
return $string;
} else {
return false;
}
}
}
$firstName = "Daniel";
$surname = "Simmons";
// Dodgy IF statement
if ($first = MyValidater::validateString($firstName) && $second = MyValidater::validateString($surname)) {
print("Success: $first $second");
} else {
print("Fail: $first $second");
}
?>
As you can see both the $first and $second variables should contain
the values held in $firstName and $surname after successfully being
validated by the Static method validateString.
However, the values of the two variables end up: $first = '1' and
$second = "Simmons".
The '1' should be "Daniel" but for some reason $first is being passed
the value '1' or TRUE. If you swap the two assignment statements over
so that $second is evaluated first, you end up with the opposite
outcome as before. $second = '1' and $first = "Daniel"
Can anyone explain why the String value "Daniel" being returned from
the class method is being changed into the int '1' for the first part
of the conditional statement only? I have had a quick look though the
PHP documentation but cannot find an explanation.
For the moment the workaround is to change the return value from the
static method to be true/false and then make $first = $firstName,
etc... upon success. But this involves more code and I would rather
find out why this way does not work.
You need to bracket your expressions:
if (($first = MyValidater::validateString($firstName)) && ($second = MyValidater::validateString($surname)))
What's actually happening is this:
if ($first = (MyValidater::validateString($firstName) && $second = MyValidater::validateString($surname)))
It would be much clearer to just do this (note this code isn't identical to what you have):
$first = MyValidater::validateString($firstName);
$second = MyValidater::validateString($surname);
if ($first && $second)
&& is higher then = in the operator precedence. add brackets and it will work.
http://www.php.net/manual/en/language.operators.precedence.php
you can read about operator precedence here.
Also, setting values inside of an if condition is usually bad practice. If you add the brackets, you will most probably see why (let $first set to false and $second set to a string) => the first will be evaluated, but since it is false then, it won't process further since it will go to the else anyways. => second will not be set correct if first = false.
Try using parenthesis
($first = MyValidater::validateString($firstName)) && ($second = MyValidater::validateString($surname)))
First is getting the result of the first function call AND the second function having a value.
= is for attributions
== is for comparisons, the data type doesn't matter
=== is for comparisons, the data type matters
What is happening is that PHP is assigning $first with “MyValidater::validateString($firstName)) && $second = MyValidater::validateString($surname)”
You need brackets around first compare and second, like this.
if ( ($first = MyValidater::validateString($firstName)) && ($second = MyValidater::validateString($surname))) {