gtilflm
gtilflm

Reputation: 1465

Checking if 4 Values are the Same

I'm looking for the simplest way to check if 4 (or more) randomly generated values are the same. I have a do-while loop here...

do {
    $var_a = mt_rand(1, 2);
    $var_b = mt_rand(1, 2);
    $var_c = mt_rand(1, 2);
    $var_d = mt_rand(1, 2);
} while ($var_a == $var_b == $var_c == $var_d);

PHP doesn't like the $var_a == $var_b == $var_c == $var_d part though. I know I could individually check each combination of $var_a, $var_b, etc. to see if they're equal, but is there a cleaner way of doing this?

Edit: Most of the answers/comments given are fine for this instance. I'm wondering about times where you could be checking, say... 20 different variables. In that case, it would be tedious to check all of the numerous combinations. Thanks to the people who have responded about this specific situation though.

Upvotes: 0

Views: 164

Answers (5)

Angelo Ara
Angelo Ara

Reputation: 11

How about this?

function checkifequal () {
  if (func_num_args() <= 1)
    return true;
  else
    for ($i = 1; $i < func_num_args(); $i++)
      if (func_get_arg[0] != func_get_arg[$i])
        return false;
  return true;
}

do {
    $var_a = mt_rand(1, 2);
    $var_b = mt_rand(1, 2);
    $var_c = mt_rand(1, 2);
    $var_d = mt_rand(1, 2);
} while (!checkifequal($var_a, $var_b, $var_c, $var_d));

Didn't check for errors, but it should work with a variable amount of parameters.

Upvotes: 1

Musa
Musa

Reputation: 97672

You could use an array

<?php
do {
    $var = array();
    $var[] = mt_rand(1, 4);
    $var[] = mt_rand(1, 4);
    $var[] = mt_rand(1, 4);
    $var[] = mt_rand(1, 4);
} while (count(array_unique($var)) != 4);
var_dump($var);

http://codepad.org/0vWi3jy5

Note I changed mt_rand(1, 2) to mt_rand(1, 4) to allow for more than 2 unique values.

Upvotes: 0

Jonathan Warden
Jonathan Warden

Reputation: 2502

Can't get much more readable than:

$var_a == $var_b && $var_a == $var_c && $var_a == $var_d

Upvotes: 0

Shiva
Shiva

Reputation: 6887

try using the AND operator

while ($var_a == $var_b && $var_b == $var_c &&  $var_c == $var_d && $var_d == $var_a);

hope that's gonna work

Regards

Shiva

Upvotes: 0

Kim Bryan Barcelona
Kim Bryan Barcelona

Reputation: 94

Try this one:

do {
    $var_a = mt_rand(1, 2);
    $var_b = mt_rand(1, 2);
    $var_c = mt_rand(1, 2);
    $var_d = mt_rand(1, 2);
} while (($var_a == $var_b)&&($var_a == $var_c)&&($var_a == $var_d));

Upvotes: 0

Related Questions