简体   繁体   中英

Put IF condition inside a variable

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.

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!

== 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.';
}

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

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) {

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 () .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM