1

I have the below code snippet which will cast an input to a float and create a variable maths operator of either > or < based on whether the float is a positive or negative number.

// allow custom variance from user input
if (isset($request->custom_variance)) {
    $variance_amount = floatval($request->custom_variance);
    ($variance_amount < 0) ? $operator = " < " : $operator = " > ";
} else {
    // set default
    $variance_amount = floatval(-50);
    $operator = " < ";
}

I then use these variables in an if statement, I have dumped here to show the output:

 var_dump((floatval($value_one) - floatval($value_two)).$operator.$variance_amount);
// returns "-51.35 < -50"

If I hard code the values I get this (It works as I want a Boolean)

 var_dump((floatval($value_one) - floatval($value_two)) < -50);
// returns true

I have done some reading on here about this and it seems like it isn't working as my operator is being interpreted as a string but I would like to avoid using the eval() function if possible.

Any suggestions?

1 Answer 1

1

You can try with the eval() with proper string expression like this with return keyword and ; and then use if condition as you wish.

$result="return ((floatval($value_one)- floatval($value_two)).$operator.$variance_amount);";
  // returns true instead of "-51.35 < -50"
  if(eval($result)){
    // do what ever you want to do
   }
Sign up to request clarification or add additional context in comments.

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.