Anish
Anish

Reputation: 5018

Adding conditions dynamically in php if condtion

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";
 }

Upvotes: 5

Views: 2976

Answers (5)

Anish
Anish

Reputation: 5018

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";
}

Upvotes: 0

amd
amd

Reputation: 21462

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";
}

Upvotes: 1

EyalAr
EyalAr

Reputation: 3170

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";
}

Upvotes: 3

Daniel
Daniel

Reputation: 3806

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;
}

Upvotes: 6

Gerald Versluis
Gerald Versluis

Reputation: 34013

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!

Upvotes: 5

Related Questions