1

I have an array of conditions :

$arrConditions = array ('>=2', '==1', '<=10');

...which I want to be able to use in an if...statement.

IE.

if (5 $arrConditions[0])
{
  ...do something
}

...which would be the same as :

if (5 >= 2)
{
  ...do something
}

Any help?

Thanks

9
  • 5
    You can use eval, but it will be horribly slow and you didn't hear it from me. Or, much preferably, you can roll up your sleeves and do it manually: switch($operator) { case '==': $result = $input == $operand; } etc. Commented Feb 25, 2013 at 12:41
  • Why do you want to do this in the first place? Commented Feb 25, 2013 at 12:43
  • Yeah, I've done it manually but was just wondering if there was a more elegant solution... Commented Feb 25, 2013 at 12:44
  • 1
    Get some refresher on basics of programming. IF requires a condition which outputs true or false. $arrCondition[0] is just a string and there is no operation happening there. which means no evaluation and no output. you can use switch case for symbols but it is impossible in case of IF. Commented Feb 25, 2013 at 12:45
  • @Abhinav...no need to be rude! That's the whole question, as in, is it possible - which, by the way, it would be using eval(). Commented Feb 25, 2013 at 12:48

2 Answers 2

2

Such a requirement is a sure sign of a bad design.
Most likely you can do that another, more usual way.

Nevertheless, never use eval for such things.
At least store each operator in pairs - an operator and operand.

$arrConditions = array (
    array('>=',2),
    array('==',1),
    array('<=',10),
);

and then use switch:

list ($operator,$operand) = $arrConditions[0];
switch($operator) { 
    case '==': 
        $result = ($input == $operand); 
        break;
    case '>=': 
        $result = ($input >= $operand); 
        break;
    // and so on
}

But again - most likely you can solve it another, much easier way.

Sign up to request clarification or add additional context in comments.

Comments

0

What about this ?

<?php

$arrConditions = array('==2', '==9', '==5', '==1', '==10', '==6', '==7');

$count = 0;
$myval = 0;
foreach ($arrConditions as $cond) {
  $str = "if(5 $cond) { return  $count;}";
  $evalval = eval($str);
  if (!empty($evalval)) {
    $myval = $count;
  }
  $count++;
}

switch ($myval) {
  case 0: echo '==2 satisfied';
    break;
  case 1: echo '==9 satisfied';
    break;
  case 2: echo '==5 satisfied';
    break;
  case 3: echo '==1 satisfied';
    break;
  case 4: echo '==10 satisfied';
    break;
  default : echo 'No condition satisfied';
}
?> 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.