0

I'm wanting to set the condition of a do-while loop with a variable. Here's my code...

$ans_type = mt_rand(1, 2);
if ($ans_type == 1){
    $condition = '$work_b != $c';
    $symbol = '=';
    $final_note = '1';
} else {
    $condition = '$work_b == $c';
    $symbol = '≠';
    $final_note = '2';      
}

do{
    $a = mt_rand(-25, 25);
    $b = mt_rand(-25, 25);
    $c = mt_rand(-25, 25);
    $d = mt_rand(-25, 25);

    if($op_1 == '–'){
        $work_b = $b * -1;
    } else {
        $work_b = $b;
    }

    if($op_2 == '–'){
        $work_d = $d * -1;
    } else {
        $work_d = $d;
    }
} while ($a == 0 || $b == 0 || $c == 0 || $d == 0 || $condition);

Note the $condition variable that I want to put in the while() part of the loop. This produces an infinite loop though.

So, is there a way to use variables as conditions in loops?

3 Answers 3

1

You can use variables as conditions, however the reason your code produces an infinite loop is because you are not changing $condition within your while loop. Therefore, if $condition evaluates to true once, it will keep evaluating to true (as it never changes in your code).

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

Comments

0

What you're trying to do can be better achieved by using normal variables:

if( blah ) {
    $conditionstate = false;
} else {
    $conditionstate = true;
}

...
} while( ... || ($work_b == $c) == $conditionstate );

If you have more varied conditions, maybe a restructure is in order. If there really is no way to restructure it, I'm hesitant to suggest it, because so many people misuse it to terrible consequences, but eval does what you're looking for and can be safe (if not fast) if used carefully. Needing to use it is usually a sign that your program has a bad structure though.

p.s. These types of random number generation problems are much better solved with code like this:

$a = mt_rand(-25, 24);
if( $a >= 0 ) {
    ++ $a;
}
// $a is -25 to 25, but never 0

$b = mt_rand(-25, 23);
if( $b >= min( $a, 0 ) ) {
    ++ $b;
}
if( $b >= max( $a, 0 ) ) {
    ++ $b;
}
// $b is -25 to 25, but never 0 or a

That can be made more elegant, but you get the idea. No need to loop at all, and guaranteed to halt.

Comments

0
$ans_type = mt_rand(1, 2);
if ($ans_type == 1){
    $condition = ($work_b != $c);
    $symbol = '=';
    $final_note = '1';
} else {
    $condition = ($work_b == $c);
    $symbol = '≠';
    $final_note = '2';      
}

You are passing $condition as a string. Just save the $condition variable as a boolean.

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.