Put IF condition inside a variable

只谈情不闲聊 提交于 2019-12-11 09:38:39

问题


Is there any way to put conditions within a variable and then use that variable in an if statement? See the example below:

$value1 = 10;
$value2 = 10;

$value_condition = '($value1 == $value2)';

if ($value_condition) {
    echo 'It works!';
} else {
    echo 'It doesnt work.';
}

I understand this may be a bizarre question. I am learning the basics of PHP.


回答1:


No need to use strings. Use it directly this way:

$value1 = 10;
$value2 = 10;

$value_condition = ($value1 == $value2);

if ($value_condition) {
    echo 'It works!';
} else {
    echo 'It doesnt work.';
}

Or to evaluate, you can use this way using ", as it expands and evaluates variables inside { ... }.

I reckon it might work! Also, using eval() is evil! So make sure you use it in right place, where you are sure that there cannot be any other input to the eval() function!




回答2:


== operator evaluates as a boolean so you can do

$value1 = 10;
$value2 = 10;

$value_condition = ($value1 == $value2);

if ($value_condition) {
    echo 'It works!';
} else {
    echo 'It doesnt work.';
}



回答3:


Just assign result of comparision to variable.

$value1 = 10;
$value2 = 10;

$value_condition = ($value1 == $value2);

if ($value_condition) {
    echo 'It works!';
} else {
    echo 'It doesnt work.';
}



回答4:


An if statement tests a boolean value. You could have something like this:

if (true) {

You can assign boolean values to a variable:

$boolValue = true;

You can use variables in your if statement:

if ($boolValue) {
   // true

In your example:

$value_condition = $value1 == $value2; // $value_condition is now true or false
if ($value_condition) {



回答5:


Depending on what you are trying to do, an anonymous function could help here.

$value1 = 10;
$value2 = 10;

$equals = function($a, $b) {
    return $a == $b;
};

if ($equals($value1, $value2)) {
    echo 'It works!';
} else {
    echo 'It doesnt work.';
}

However, I would only do it like this (and not with a regular function), when you make use of use ().



来源:https://stackoverflow.com/questions/26589974/put-if-condition-inside-a-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!