Henrik Petterson
Henrik Petterson

Reputation: 7094

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.

Upvotes: 2

Views: 6740

Answers (5)

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167172

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!

Upvotes: 4

kero
kero

Reputation: 10638

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

Upvotes: 2

Brad
Brad

Reputation: 163234

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

Upvotes: 1

Esse
Esse

Reputation: 3298

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

Upvotes: 1

Gianluca Ghettini
Gianluca Ghettini

Reputation: 11628

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

Upvotes: 1

Related Questions