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;");
Related
I have assigned a condition into a variable. Then I tried to put that variable as a parameter of a if statement. But the code is not working. Please check my code:
$a = 8;
$final_str = '$a == 10';
if($final_str) {
echo 'Output 1';
} else {
echo 'Output 2';
}
The desired output should be Output 2. But it is not working. I always see Output 1. Please help me in this case.
Thanks in advance!
As per your request, the real problem here is this line of code:
$final_str = '$a == 10';
Although you have said that you cannot change the first two lines of code as it is what you have intended, I think that what you have intended and the result of this are two different things.
You see, you are defining '$a == 10' which is interpreted literally as a string value.
So you are trying to do something like:
if ('some string') ...
The result of this is true because a string that is not empty is a truthy value.
I think your intention however, was to test if the variable $a is equal to the integer value of 10?
In which case you actually need to do:
$final_str = $a == 10;
The result of this can be true or false depending on whether the variable $a is equal to 10 or not, that way your if condition will reflect the desired result?
EDIT:
If however you are trying to create some PHP code dynamically within your string you'd need to run it through eval and here is more information relating to the usage.
EDIT 2:
I would rather try to re-factor this into something more like:
$thisPage = 8;
$truthyPages = array(10,20);
if (in_array($thisPage,$truthyPages)) {
echo 'positive output';
} else {
echo 'negative output';
}
Or maybe even:
$a = 8;
// Step 1
$final_result = $final_result || $a == 10;
// Step 2
$final_result = $final_result || $a == 20;
if ($final_result) {
echo 'success';
} else {
echo 'failure';
}
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
I have this php variable :
$temp = '<script>document.write(sessionStorage.login_condetion);</script>';
When I echo the value of $temp it gives me a number for example 1 and when I use gettype it tells me the type of $temp is string. I want to use the value of the $temp as a condition in if clause but it does not work no matter how I change it for example I tried all the following cases :
if($temp == 1){}
if($temp === 1){}
if($temp == '1'){}
if($temp === '1'){}
if($temp == "1"){}
if($temp === "1"){}
I do not know why it is not working in the if clause ? could it be because $temp has <scritp> tag ? and if it is how could I extract the value that I want it as a number ?
PS: I try to cast as following:
$temp1 = (int)$temp;
But it does not work if the value of $temp is one it gave me after casting a zero.
Yours $temp variable is just a regular string.
But when you echo it on a page, the javascript engine will evaluate it and add 1 to the DOM, so it seems like the value of it is 1 but actually it's really not.
The following two ifs produced different results(first if echos hi, second does not), why? why didn't the variable assignment on $t work? is this due to $t's local scope inside the if conditional?
if(isset($_REQUEST["test"]) && $t=trim($_REQUEST["test"]) && !empty($t)){
echo 'hi'
}
if(isset($_REQUEST["test"]) && $t=trim($_REQUEST["test"])){
if(!empty($t))echo 'hi'
}
&& has a higher precedence than =, hence the first expression is evaluated as:
isset($_REQUEST['test']) && $t = (trim($_REQUEST['test']) && !empty($t))
Since !empty($t) is evaluated before anything is assigned to $t, the expression is false. You could fix this by explicitly setting parentheses, or by using a less awkward way to write it:
if (isset($_REQUEST['test']) && trim($_REQUEST['test'])) {
echo 'hi';
}
trim($_REQUEST['test']) will evaluate to true or false just by itself, no empty necessary. If you actually need the trimmed value later, you can save it like so:
if (isset($_REQUEST['test']) && ($t = trim($_REQUEST['test']))) {
echo 'hi';
}
If you make minor modification like this in your code:
if(isset($_REQUEST["test"]) && ($t=trim($_REQUEST["test"])) && !empty($t)){
echo '1: hi<br/>';
}
if(isset($_REQUEST["test"]) && $t=trim($_REQUEST["test"])){
if(!empty($t))
echo '2: hi<br/>';
}
Then both 1: hi and 2: hi will be printed. Difference is parenthesis around first $t assignment.
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))) {