1

i need help with this, currently my idea here is to only use variables to perform an IF statement, these variables are supposed to be taken from a database (ive got that down) but i dont know how to create an if statement that can use all 3

<?php
$Anum="10";
$Bnum="30";
$MOD="<=";

if ($Anum $MOD $Bnum)
{
echo $Anum, " is smaller than ", $Bnum;
}
else
{
echo "$Anum, " is not smaller than ", $Bnum;
}
?>
1

3 Answers 3

1

This will work for you:

$Anum="10";
$Bnum="30";
$MOD=">=";

eval("\$result = ($Anum $MOD $Bnum) ? true : false;");

if ($result) {
    echo "$Anum is smaller than $Bnum";
} else {
    echo "$Anum is not smaller than $Bnum";
}

Output:

10 is not smaller than 30

BUT.

PHP has variable variables and can expand strings into variables with it, but it does not work for language constructs, only for variables. ">=" is a comparison operator, so by this:

$Anum.$MOD.$Bnum
//or this
"$Anum $MOD $Bnum"
or this
"{$Anum} {$MOD} {$Bnum}"

You can only get a string, which will always give you true when using with if statement. To achieve what you want with your strategy you need to use eval. But it is a function, that should be avoided, unless you have enough experience and knowledge to use it with all responsibility and caution.

Sign up to request clarification or add additional context in comments.

3 Comments

Yes this will work as he expected.What about my solution ?
@Sree a little verbose but will work for this case too.
Was sort of hoping to not use eval, but thank you all the same! i guess i will have to use this then.
0

In php

$MOD="<="; will assign as a string (double quoted characters)

For assigning this as a comparison operator you have to do something like this

 <?php
    $Anum=10;
    $Bnum=30;
    $MOD=">=";
     switch ($MOD) {
            case '<=': if($Anum <= $Bnum){ echo $Anum ." is smaller than ". $Bnum;} else{ echo $Anum ." is not smaller than ". $Bnum; }; break;
            case '>=': if ($Anum >= $Bnum){ echo $Bnum ." is smaller than ". $Anum;} else{ echo $Bnum ." is not smaller than ". $Anum; }; break;
           }

    ?>

2 Comments

Thanks for the help! this will work too, appreciate your help :)
No Problem .Glad to help :)
0

try this

<?php
$Anum="10";
$Bnum="30";
$MOD="<=";

$result = eval("if($Anum $MOD $Bnum){return true;}else{return false;}");

if ($result)
{
echo $Anum. " is smaller than ". $Bnum;
}
else
{
echo "$Anum, is not smaller than ". $Bnum;
}?>

here

eval("if($Anum $MOD $Bnum){true}else{false}");

will execute the if condition and return the result and save it to some variable, and put this variable to if statment.

1 Comment

Did you run you code? Your eval statement won't run.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.