Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PHP Dynamic operator usage

I want to be able to use the operator between two values ​​according to the value that will come from the database.

For ex:


$operator = '<='; // this can be '<=' or '<' or '>=' etc.

// I need like this something
if ($value1 $operator $value2) {
    //
}

How can i do?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can write a function with a switch case inside. like that:

$operator = '<='; // this can be '<=' or '<' or '>=' etc.

// I need like this something
$value1 = 2;
$value2 = 3;


function dyn_compare ($var1, $operator, $var2) {
    switch ($operator) {
        case "=":  return $var1 == $var2;
        case "!=": return $var1 != $var2;
        case ">=": return $var1 >= $var2;
        case "<=": return $var1 <= $var2;
        case ">":  return $var1 >  $var2;
        case "<":  return $var1 <  $var2;
    default:       return true;
    }   
}

//Then you can use

if (dyn_compare($value1, $operator, $value2)) {
    echo 'yes';
}

Alternatively you can work with match like @Justinas suggested. But this only works with php 8 and upwards

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading