Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

139
Vistas
Assigning a if statement's condition to a variable

Is it possible to assign a conditional statement into a variable and use it in an if statement? For example, I have the following code where the condition in the if statement will change from time to time:

<?php       
   $x = 2;
   
   //This "x > 5" value will come from a database
   $command = "x > 5";//Some times this value might be x > 5 || x == 1
  
   if($command)//This will always be true no matter what since the content of the $command is not empty
        echo "x is bigger than 5";
   else
        echo "x is smaller than 5";//I want this line to get executed since x is smaller than 5 in this case
?>

Expected output is x is smaller than 5, but what I get is x is bigger than 5

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

You need to use eval(). $command will have to contain $ before the variables so it's valid PHP syntax.

$x = 2;
$command = '$x > 5';
$result = eval("return ($command);");
if ($result) {
    echo "x is bigger than 5";
} else {
    echo "x is smaller than 5";
}

Since eval() can execute arbitrary code, you should be extremely careful about what you allow to be put into $command.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda