Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 929
Henrik Petterson Avatar asked Jan 29 '26 21:01

Henrik Petterson


2 Answers

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!

like image 141
Praveen Kumar Purushothaman Avatar answered Feb 01 '26 11:02

Praveen Kumar Purushothaman


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

like image 22
kero Avatar answered Feb 01 '26 10:02

kero



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!