This question already has answers here:
How to dynamically pass condition of if statement
(2 answers)
Closed 1 year ago.
This post was edited and submitted for review 1 year ago and failed to reopen the post:
Original close reason(s) were not resolved
I try to check a condition using php variable like..
if ($amount. $row['condition']. $row['amount']) {
return true;
} else {
return false;
}
but the condition always return true value ,i also echo the single variable it will show the value and also do dd($amount. $rom['condition']. $rom['amount']); it will show "500>1000" ,i remove the double qutes and manually past value in if condition it will show false with this condition, how to solve and write this condition ?
I would use a match or switch like so:
<?php
# match php 8+
$result = match ($row['condition']) {
'==' => $amount == $row['amount'],
'<' => $amount < $row['amount'],
'>' => $amount > $row['amount'],
};
# switch
switch ($row['condition']) {
case '==':
$result = $amount == $row['amount'];
break;
case '<':
$result = $amount < $row['amount'];
break;
case '>':
$result = $amount > $row['amount'];
break;
};
var_dump($result);
Try online
I've never faced such scenario, but I would imagine something like:
if ($row['condition'] == "==") {
if ($amount == $row['amount'])
return true
else
return false
}
if ($row['condition'] == ">") {
if ($amount > $row['amount'])
return true
else
return false
}
if ($row['condition'] == "<") {
if ($amount < $row['amount'])
return true
else
return false
}
Use eval()
$condition = $amount. $row['condition']. $row['amount'];
if (eval("return $condition;")) {
return true;
} else {
return false;
}
Important Note: Before using eval() make sure you have sanitized user input while inserting into database.
Docs for input sanitization : https://www.cloudways.com/blog/prevent-laravel-xss-exploits/
Related
This question already has answers here:
The 3 different equals
(5 answers)
Closed 5 years ago.
why the IF(the lastest one with else if and else) is doing all the time only first condition and only the first part ($filtry_1value[$key] = 'min_cena'), even if the condition shouldnt be true. I have another solution (less dynamic), if I will not fix this one, but I would like to know, why it is not working... I think it will be a trivial thing, but I cannot see it.
PS: I am working with laravel.
$filtry_1value = ['stat', 'lokalita', 'patro', 'min_cena', 'max_cena', 'min_uzitna_plocha', 'max_uzitna_plocha'];
foreach ($filtry_1value as $key => $filtr_1value) {
$filtr_1value = \Request::has($filtr_1value) ? \Request::get($filtr_1value) : null;
if(!empty($filtr_1value)){
if ($filtry_1value[$key] = 'min_cena' OR $filtry_1value[$key] = 'min_uzitna_plocha') {
$query->where(substr($filtry_1value[$key], 4),'>=',$filtr_1value);
}
elseif ($filtry_1value[$key] = 'max_cena' OR $filtry_1value[$key] = 'max_uzitna_plocha') {
$query->where(substr($filtry_1value[$key], 4),'<=',$filtr_1value);
}
else {
$query->where($filtry_1value[$key],'=', $filtr_1value);
}
}
}
may be-
foreach ($filtry_1value as $key => $filtr_1value) {
$filtr_1value = \Request::has($filtr_1value) ? \Request::get($filtr_1value) : null;
if(!empty($filtr_1value)){
if ($filtry_1value[$key] == 'min_cena' OR $filtry_1value[$key] == 'min_uzitna_plocha') {
$query->where(substr($filtry_1value[$key], 4),'>=',$filtr_1value);
}
elseif ($filtry_1value[$key] == 'max_cena' OR $filtry_1value[$key] == 'max_uzitna_plocha') {
$query->where(substr($filtry_1value[$key], 4),'<=',$filtr_1value);
}
else {
$query->where($filtry_1value[$key],'=', $filtr_1value);
}
}
}
You need to use the double equal sign for comparisons. == not a single =
Your if's should look like:-
if ($filtry_1value[$key] == 'min_cena' OR $filtry_1value[$key] == 'min_uzitna_plocha') {
// ...
} elseif ($filtry_1value[$key] == 'max_cena' OR $filtry_1value[$key] == 'max_uzitna_plocha') {
// ...
}
So I am new to PHP, and am currently just doing a little project as practice, I've managed to get down a few lines of code without falling over... but am a bit stuck here.
Essentially, what my script currently does is check three different variables that I have set (each a true/false option) and distinguishes if there is only one true option selected (out of the 3 options, only one can be true, the other 2 must be false). If only 1 value is set to true, the rest of the code runs; if multiple values are set to true, or no values are set to true, it shows an error prompt for the user.
Once this check is done, I wanted to then set the value of $name for example, based on records linked to the relevant variable that is true... This is what I have come up with, but it doesn't seem to work...
if ($value1 == "true") {$name = $result1;}
else if ($value2 == "true") {$name = $result2;}
else if ($value3 == "true") {$name = $result3;}
else exit (0)
So i essentially want to set the $name variable by identifying which of the 3 value variables is true, and then setting $name with the relevant variable retrieved in the $result
Any help would be appreciated. And before anyone goes off on one... I know I may sound a bit mad... but we all have to start somewhere!!
Thanks
It would look much nicer with a switch:
switch(true){
case $value1:
$name = $result1;
break;
case $value2:
$name = $result2;
break;
case $value3:
$name = $result3;
break;
default:
exit();
}
In case you need to make sure only one of the statements is true, validate that prior using this:
//In case you need to make there is only a single true statement
$found = false;
for($i=1; $i<4; $i++) {
$value = "value".$i;
if($$value) {
if($found) {
exit("More than one 'true' statement");
}
$found = true;
}
}
Dracony's answer looks nice indeed, but will fail when multiple values are set to true. For more flexibility, you should consider mapping the values into arrays, and tracking the state (amount of values that are true) with a flag variable. Find a fully commented example that will satisfy all conditions below. Additionally, this code will work with arrays of any length (you can add conditions by simply putting more values in $values and $results).
// store the data in arrays for easier manipulation
$values = array($value1, $value2, $value3);
$results = array($result1, $result2, $result3);
// set a flag to check the state of the condition inside the loop
// it keeps track of the index for which the value is true
$flag = -1;
$name = NULL;
// use for and not foreach so we can easily track index
for ($i = 0; $i < count($values); $i++) {
// if no index has been found 'true' yet, assign the current result.
if ($values[$i] === true) {
if ($flag === -1) {
$flag = $i;
$name = $results[$i];
}
// if a 'true' value has been found for another index
// reset the name var & stop the loop
if ($flag > -1 && $flag !== $i) {
$name = NULL;
break;
}
}
}
if ($name) {
// run code when only 1 value is true
} else {
exit();
}
I am trying to validate 3 scenarios but something is wrong and the if statements are not being honored properly
Here are the scenarios I need to work:
If the string "2.5.4.15" exists in array then output "Extended Validation".
If the string "2.5.4.15" does NOT exist in array then output "Organization Validated".
If the string "id-at-organizationName" does NOT exist in array then output "Domain Validated".
I am getting incorrect results. For example, if the data I am parsing does contains "2.5.4.15" for some reason its returning "Domain Validated" ??
Here is my code:
if(isset($cert['tbsCertificate']['subject']['rdnSequence'])) {
$EV = array('2.5.4.15');
$org = array('id-at-organizationName');
$count = count($cert['tbsCertificate']['subject']['rdnSequence']);
for($i = 0; $i < $count; $i++) {
if(in_array($cert['tbsCertificate']['subject']['rdnSequence'][$i][0]['type'], $EV)) {
$validation = "<tr><td>Validation</td><td>Extended Validation (EV)</td></tr>";
echo $validation;
break;
}
if(!in_array($cert['tbsCertificate']['subject']['rdnSequence'][$i][0]['type'], $EV)) {
$validation = "<tr><td>Validation</td><td>Organization Validated (OV)</td></tr>";
echo $validation;
break;
}
if(!in_array($cert['tbsCertificate']['subject']['rdnSequence'][$i][0]['type'], $org)) {
$validation = "<tr><td>Validation</td><td>Domain Validated (DV)</td></tr>";
echo $validation;
break;
}
}
}
-- UPDATE --
I removed the break; and I can see it's now returning multiple results before it gives our the correct one (highlighted in red the correct match).. but why is it returning the bogus response instead of just returning the correct response the first time ?
-- UPDATE 2 --
I think I understand the results I am getting, it seems to be outputting result for each iteration where the string is not found. Whereas what I want to do is return one response.
I think then because of this perhaps using a loop is not the answer. Is there a way to search the whole array for a string and output the result instead of looping through each array ?
I didn't understand why are you using 'array' to store single values, you can simple compare strings.
In case the field can match only to one option - you can use if..elseif or even better - switch.
Please notice that your $validation variable will always overwrite itself in every irritation. So, If you're looking for a specific row - you should mention it. If you're looking for one multi-result in the end, you need to store that data in another array.
In continuation to the chat, let me break the scenarios of the key's value:
If 2.5.4.15 exists in the array - return EV
If it (1) doesn't exist but 'id-at-organizationName' does - return
If it (1) doesn't exist and (2) also doesn't exist - return
For the first scenario I used break since if it exists we don't need to continue to check the rest of the array, also it's automatically means that the 2 other conditions could never exist. EDIT also added a break to the second scenario condition.
Here is my suggestion: (Please check it and share the output/problems in the chat until will accomplish to solve your problem)
if(isset($cert['tbsCertificate']['subject']['rdnSequence'])) {
$count = count($cert['tbsCertificate']['subject']['rdnSequence']);
for($i = 0; $i < $count; $i++) {
$value = $cert['tbsCertificate']['subject']['rdnSequence'][$i][0]['type'];
if($value == "2.5.4.15") {
$output = "EV";
break;
} else {
if($value == "id-at-organizationName") {
$output = "OV";
break; //Edit 1
} else {
$output = "DV";
}
}
}
echo $output;
}
You echoes bad variables:
for($i = 0; $i < $count; $i++) {
if(in_array($cert['tbsCertificate']['subject']['rdnSequence'][$i][0]['type'], $EV)) {
$validation = "<tr><td>Validation</td><td>Extended Validation (EV)</td></tr>";
echo $validation;
break;
}
if(!in_array($cert['tbsCertificate']['subject']['rdnSequence'][$i][0]['type'], $EV)) {
$validation1 = "<tr><td>Validation</td><td>Organization Validated (OV)</td></tr>";
echo $validation1; // $validation1 instead of $validation
break;
}
if(!in_array($cert['tbsCertificate']['subject']['rdnSequence'][$i][0]['type'], $org)) {
$validation2 = "<tr><td>Validation</td><td>Domain Validated (DV)</td></tr>";
echo $validation2; // $validation2 instead of $validation
break;
}
}
The second thing is that for this task is better to use elseif instead of 3 ifs:
for () {
if () {
// validation
} elseif () {
// validation 1
} elseif () {
// validation 2
}
}
I have created this function that correctly displays the infinity symbol when trying to enter 0 into the Y text box. However I still get the division by zero error... here is my code.
here is the case for switch statment
case '/':
$prod = $x / $y;
break;
hh
//check for divide by 0
function check0($y)
{
if ($y == 0)
throw new Exception ($prod = "∞");
return FALSE;
}
try
{
check0($y);
$prod = $x /$y;
}catch(Exception $zero){
echo $zero->getMessage();
}
First: you are doing a division at the second line code (which can be devision by zero).
Second: no need to return false in your method since you are throwing an error.
Third: Why using an exception here and not just let you method return true of false and check on that before executing the devision.
Fourth: Why having a method if you only need to check on the value of $y. Calling the method or including an if-statement requires both just one line of code.
So, why can't it just be like:
case '/':
if($y > 0)
$prod = $x / $y;
break;
This is because you actually do the division near the top (in the case).
Your logic feels ... mmm well entangled.... Here have a look at this:
<?php
function divide($x, $y) {
if ( $y === 0 )
throw new Exception("Divide By Zero");
return $x/$y;
}
try {
$product = divide(3, 0);
}
catch(Exception $e) {
if ( $e->getMessage() == "Divide By Zero" )
$product = "∞";
else
$product = NULL;
}
print "Product is $product\n";
?>
You must call check0() before division. You should return FALSE if y == 0, TRUE otherwise.
If return TRUE then do division. However it's not necessary call a method to do this!
In my case everything works fine. Be sure, you are not trying to use division earlier in your script, because it look's like.
case '/':
$prod = $x / $y;
break;
starts before your function call.
1st i have to say that i am not php professional and this is my 1st time to use return().
so here is the code.
i need to return false and the number of minutes left from the function.
if(!checkIpn())
$err[]='you need to wait'.$nresting.'minutes before you send another request';
function checkIpn()
{
$useripe = 0;
if ( isset($_SERVER["REMOTE_ADDR"]) ) { $useripe = $_SERVER["REMOTE_ADDR"] ; }
else if ( isset($_SERVER["HTTP_X_FORWARDED_FOR"]) ) { $useripe = $_SERVER["HTTP_X_FORWARDED_FOR"] ; }
else if ( isset($_SERVER["HTTP_CLIENT_IP"]) ) { $useripe = $_SERVER["HTTP_CLIENT_IP"] ; }
$query = "SELECT * FROM table WHERE ip = '$useripe' AND status = 'pending' ORDER BY id ASC";
$result = mysql_query($query) or die(mysql_error());
$num_rows = mysql_num_rows($result);
if ( $num_rows > 0 )
{
$str_today = date("Y-m-d H:i:s");
$i=1;
while($row = mysql_fetch_assoc($result))
{
$str_start = $row['date'];
$str_start = strtotime($str_start);
$str_end = strtotime($str_today);
$nseconds = $str_end - $str_start;
$nminutes = round($nseconds / 60);
if ( $nminutes > 120 )
{ return true; }
else {
$nresting = 120 - $nminutes;
return false; }
$i++;
}
}
else { return true; }
based on Tadeck answer below.i did it like this:
$result = checkIpn();
if($result[0]==false)
$err[]='you need to wait '.$result[1].' minutes before you send another request';
thank you Tadeck.
If you want to return two different variables using single call, you can use something like:
return array(true, 0);
or
return array(true);
in first case (when returning success) and
return array(false, $minutes);
in second case (returning failure).
Then you can check it that way:
$result = checkIpn();
if ($result[0]) {
echo 'Success.';
} else {
echo 'Failure. Minutes to wait: '.$result[1];
}
I hope this helps.
EDIT:
If I understand you correctly, you return true or the number of minutes > 0 (larger than zero). Thus you can use such return in case of success:
return true;
and this in case of failure:
return $minutes;
Then you will be able to use it in the code in the following way:
$result = checkIpn();
if ($result === true) {
echo 'Success';
} else {
echo 'Failure. Minutes to wait: '.$result;
}
And I would like to advise you to properly document such function, so that no one is surprised when it returns integer instead of boolean ;)
You can return an array instead of booleans, which allows you to return more than one value:
return array('success'=>FALSE, 'nminutes'=>$nminutes);
But as an alternative, you can just return NULL if the function is successful and return the number of minutes if not. Then you don't need TRUE/FALSE at all.
if ($nminutes > 120)
{
return NULL;
}
else
{
return $nminutes;
}
Check the success like so:
if (checkIpn() !== NULL) // you have minutes left
else // no minutes left - your TRUE case.
You could return an array containing as many things as you like.
In php you can return an array and use the list() function to unpack the values.
function myfn() {
return array(true, 120);
}
...
list($retval, $minutes) = myfn();
This is generally pretty bad style though and I would recommend finding a way to accomplish what you need with 1 return value.