I am trying to add a condition dynamically in the if condition . But it is not working . Please help me to fix the issue.
I am trying a code like this
$day_difference = "some integer value";
if(sheduled_time == 'evening'){
$condition = '>';
}else{
$condition = '==';
}
then
if($day_difference.$condition. 0){
echo "something";
}else{
echo "h";
}
An alternative to gerald's solution; I would suggest that you use a function that validates the inputs using a switch-case operation:
function evaluate ($var1, $operator, $var2)
{
switch $operator
{
case: '<': return ($var1 < $var2);
case: '>': return ($var1 > $var2);
case: '==': return ($var1 == $var2);
}
return null;
}
What you need is the eval() method.
I.e.
$var1 = 11;
$var2 = 110;
$cond1 = '$var1 > $var2';
$cond2 = '$var1 < $var2';
if(eval("return $cond1;")){
echo $cond1;
}
if(eval("return $cond2;")){
echo $cond2;
}
As justly noted beneath, you should exercise the necessary precautions when using this method!
This is not the way to do this.
Just define a function which returns true if the desired conditions are met.
For example, we can define the function decide which receives two arguments, $day_difference and $scheduled_time:
function decide($day_difference, $scheduled_time)
{
if($scheduled_time == 'evening')
{
return $day_difference > 0;
}
else
{
return $day_difference == 0;
}
}
And use it like so:
if( decide($day_difference, $scheduled_time) )
{
echo "something";
}
else
{
echo "h";
}
according to your requirements this can be done using the PHP eval() function which i don't recommend using it only when necessary.
you can check When is eval evil in php?
you can use the below script instead:
if( $sheduled_time == 'evening' && $diff > 0 )
{
echo "This is the Evening and the Difference is Positive";
}
else if($diff == 0)
{
echo "This is not evening";
}
Thankyou for helping me solve my question
I solved this in another way
$day_difference = "some integer value";
$var1 = false ;
if($sheduled_time == 'evening_before'){
if($day_difference > 0 ){
$var1 = true ;
}
}else{
if($day_difference == 0 ){
$var1 = true ;
}
}
if($var1 === true){
echo "something";
}else{
echo "h";
}
Related
I am trying to reduce/simplify the following code as it looks to have repeated elements:
<?php
if ($condition == true) {
if ($a > $b*0.5) {
echo "successful";
}
else {
echo "missed";
}
}
else {
if ($a > $b) {
echo "successful";
}
else {
echo "missed";
}
}
I don't want to use functions because if I did, I would have to define all the database things again.
<?php
if ( (condition1 && ($a > $b*0.5)) || (!condition1 && ($a > $b)) ) {
echo "successful";
else {
echo "missed";
}
?>
Your Code is missed Two (Semicoloumns)}.
Try By this
<?php
$a == 2;
$b == 4;
if ($a == 2 && $a > $b*0.5) {
echo "Suuccess";
}elseif($a != 2 && $a > $b){
echo "Suuccess";
}else{
echo "Fails";
}
In order to simplify your conditions, if the output is boolean (so only two outcomes possible) you could go with either one as default and only change it to the other depending on your decisions.
<?php
$outcome = false;
if($condition1 && ($a > ($b * 0.5))) {
$outcome = true;
}
else if($a > $b) {
$outcome = true;
}
if($outcome) {
echo "succesful";
}
else {
echo "missed";
}
This also combines the technique proposed by Sofyan Thayf to use boolean operators to merge conditions.
Another approach is to put the condition into a function and return early if succesful and have a missed fallthrough like
<?php
function decide($a, $b, $condition1) {
if($condition1 && ($a > ($b * 0.5)))
return true;
if($a > $b)
return true;
return false;
}
if(decide($a, $b, $condition1)) {
echo "succesful";
}
else {
echo "missed";
}
Both approaches enable you to extract the "same code" (being the echo) and IMHO add to readability and extensibility.
<?php
$factor = $condition ? 0.5 : 1;
if ($a > $b * $factor) {
echo "Hit";
}
else {
echo "Miss";
}
Could be further reduced using two ternary operators:
echo $a > $b * ($condition ? 0.5 : 1)
? 'Hit'
: 'Miss';
Ternary operators are useful shorthand for if/else conditionals.
I want to check different conditions into if statement based on different scenario (Will get the $status value as 'Y' or 'N'). Please check the code below and let me know the issue here.
$fstrto = "10";
$cstrto = "7";
if($status == 'N')
{
$cond = "$fstrto <= $cstrto";
}
else
{
$cond = "$fstrto >= $cstrto";
}
if($cond)
{
echo "Success";
}
This code is not working as it takes the "$fstrto <= $cstrto" as variable.
Remove the quotes. Use intval/doubleval if the input is a string as in $fstrto = intval($fstrto);.
$fstrto = 10;
$cstrto = 7;
if($status == 'N')
{
$cond = $fstrto <= $cstrto;
}
else
{
$cond = $fstrto >= $cstrto;
}
if($cond)
{
echo "Success";
}
Why it works: $cond is being assigned the value of a boolean expression, the values of which can be true or false. if($cond) just checks whether $cond is true or false
what is need to do is when using string as a php code use
eval — Evaluate a string as PHP code
Use below code work like charm:
$fstrto = "10";
$cstrto = "7";
if($status == 'N')
{
$cond = "$fstrto <= $cstrto";
}
else
{
$cond = "$fstrto >= $cstrto";
}
if(eval("return $cond;"))
{
echo "Success";
}
IMPORTANT:
Use of eval is highly discouraged
NEVER EVER use eval with params by POST/GET without sanitize them
When is eval evil in php?
You "$fstrto <= $cstrto" is a string now a compare statement.
$fstrto = "10";
$cstrto = "7";
if( ($status == 'N' && $fstrto <= $cstrto) || ($status != 'N' && $fstrto >= $cstrto) )
{
echo "Success";
}
Potentially turn it into a function that funnels into a switch statement like so:
function evaluateCondition($status, $a, $b) {
switch ($status) {
case 'Y':
return $a >= $b;
break;
case 'N':
return $a <= $b;
break;
default:
// Error Log. Unknown Status.
}
}
Any future addition can be appended onto the switch statement as necessary, if it gets more convoluted have each case return a separate function() to improve readability.
In terms of the current version you could use it like so:
$result = evaluateCondition('Y', 5, 6);
var_dump($result); // bool(false)
Hope that helps.
$fstrto = "10";
$cstrto = "7";
$cond = false;
if($status == 'N')
{
if($fstrto <= $cstrto){
$cond = true;
}
}
else
{
if($fstrto >= $cstrto){
$cond = false;
}
}
if($cond)
{
echo "Success";
}
I am not understanding this ?quirk? of php at all... as I am looking over other peoples code I see that some people leave out the else statement completely and just place a "return false;" statement.
It seems this trick only works for the return statement and as you can see in the cases below it does not work when echoing text.
This is strange, take case two for example, surely this function is read proceeduraly, so the function will return "true" inside the if statement because the condition is met however when it leaves the if/else statement it should return FALSE because there is no ELSE statement. This DOES NOT happen and the function still returns true.
I can't make sense of this so hopefully someone can explain?
// Case 1
function checkNumber1($number) {
if ($number === 10) {
return true;
} else {
return false;
}
}
$number = 10;
var_dump(checkNumber1($number)); // Returns true
// Case 2
function checkNumber2($number) {
if ($number === 10) {
return true;
}
return false;
}
$number = 10;
echo '<br>';
var_dump(checkNumber2($number)); // Also returns true??
// Case 3
function checkNumber3($number) {
if ($number === 10) {
echo 'true' . '<br>';
} else {
echo 'false' . '<br>';
}
}
$number = 10;
echo '<br>';
checkNumber3($number); // Returns true
// Case 4
function checkNumber4($number) {
if ($number === 10) {
echo 'true' . '<br>';
}
echo 'false' . '<br>';
}
$number = 10;
checkNumber4($number); // Returns true and then false???
The return statement in a function immediately ends execution of the current function and returns control.
I am checking 3 variables are equals to zero inside if condition , currently i am doing some thing like this
if($diff_colour_code==0 && $diff_upholstery_code==0 && $big_diff==0 )
is there any better way to do this
I am thinking a way like
if($diff_colour_code==$diff_upholstery_code==$big_diff==0 )
Please help , Thanks in advance .
This should work for you:
You can give the function as many arguments as you need!
<?php
$diff_colour_code = 0;
$big_diff = 0;
$diff_upholstery_code = 0;
function zeroCheck() {
foreach(func_get_args() as $arg)
if($arg == 0)
continue;
else
return false;
return true;
}
if (zeroCheck($diff_colour_code, $big_diff, $diff_upholstery_code))
echo "all are 0!";
?>
you can use ! as :
if(!$diff_colour_code && !$diff_upholstery_code && !$big_diff )
You could do something like this:
$var1 = 0;
$var2 = 0;
$var3 = 0;
$array = compact("var1", "var2", "var3");
$countValues = array_count_values($array);
if($countValues[0] == count($array)){
echo "yes";
}else{
echo "no";
}
or this
if(($var1 == 0 && $var1 == $var2 && $var2 == $var3)){
echo "yes";
}else{
echo "no";
}
In this elementary code, I check if a record exists with a particular itemId for a particular user and country.
The record returns 1 inside the function, but when it's outside, it's something totally different.
function recordExists(&$d) {
global $conn, $userId, $userCountryCode;
$sqlFindRecord = "select count(itemId) as recordCount from onr_items_mod where itemTempId = :itemTempId and itemStatus IN(0,5,8) and itemPublishedStatus = 2 and itemUserId = :userId and itemUserCountryCode = :userCountryCode";
$countRecord = $conn->prepare($sqlFindRecord);
$countRecord->execute(array(
":itemTempId" => $d,
":userId" => $userId,
":userCountryCode" => $userCountryCode
));
$countRecord->bindColumn('recordCount',$d);
echo 'This is D '.$d.' ---';
$row = $countRecord->fetch();
if($d == 0) {
return $d;
} elseif ($d == 1) {
return $d;
} else {
return false;
}
}
$d = 'US01'
if(recordExists($d) == 0) { //If the function returned 0
echo $d;
echo 'Was Zero';
} elseif (recordExists($d) == 1) { //If the function returned 1
echo $d;
echo 'Was One';
} else {
echo $d;
echo 'Neither Zero or One';
}
After I do the above, it's always 'Neither Zero or One'. Why is this? I tried the entire morning, but just cannot figure a way to sort this out.
This works, but not the above
function counter(&$a) {
if($a == 0) {
return $a;
} elseif ($a == 1) {
return $a;
} else {
return false;
}
}
$a = 1;
if(counter($a) == 0) {
echo $a;
} elseIf (counter($a) == 1) {
echo $a;
} else {
echo 'Umm...'.$a;
}
It will always be 'Neither Zero or One' why? Let's seee how it works
1. $d = 'US01'
2. if(recordExists($d) == 0) { //If the function returned 0
3. echo $d;
4. echo 'Was Zero';
5. } elseif (recordExists($d) == 1) { //If the function returned 1
6. echo $d;
7. echo 'Was One';
8. } else {
9. echo $d;
10. echo 'Neither Zero or One';
11. }
First $d is equal US01. It's ok. But after pass line #2 $d == 1 because you have set it in function (you have pass $d by reference).
So if statement in #2 line will return false beacuse thera are some records in database with itemTempId = 'US01'.
But now in the second if statement in line #5 variable $d = 1. So I suposse that you don't have any record with that itemTempId in your database. So the second statement (line #5) will also return false.
In my opinion you shouldn't pass it by reference.
EDIT
If you want to check if item exist in databse then yopu can ask only once. I really don't know what your goal is. But maybe this will be good
$d = 'US01';
$ret = recordExists($d);
if ($ret === 0) {
echo 'Was zero';
} elseif ($ret === 1) {
echo 'Was one';
} else {
echo 'Something else';
}
try to insert that into session variable and retrieve it in another method.
Hope it'll help.