Reputation: 2063
I am attempting to create one array with user entered numbers and then another array with random numbers between 0 and 9. I then want to compare the 2 arrays and when they match, echo out a result.
At the moment I'm receiving a fatal error:
Maximum execution time of 30 seconds exceeded
I know the elements are entered in the array correctly after using var_dump
.
$i = 0;
while(!in_array($lotArray, $userArray)) {
$i ++;
}
echo "YOU WON it took".$i."times";
?>
Upvotes: 0
Views: 48
Reputation: 20899
Using an iterative approach to compare each number is Oh(n²)
because you have to compare X times X numbers.
Instead, take a simple approach:
Oh(n log n)
each)Oh(n)
)Oh(n)
)like
$arr1 = array(1,2,3);
$arr2 = array(2,3,1);
asort($arr1);
asort($arr2);
$string1 = implode($arr1, "_"); // "1_2_3"
$string2 = implode($arr2, "_"); // "1_2_3"
if ($string1 == $string2){
echo "You've won!";
}
Upvotes: 2
Reputation: 1784
If you wan to compare two arrays (all numbers must be the same, in the same order) :
$a1 = array(1, 9, 4);
$a2 = array(1, 9, 4);
if (count(array_diff($a1,$a2)) == 0)
echo "Both array match";
Upvotes: 1
Reputation: 1875
this works fine
$count = //your wish of getting random numbers.
$randarr = range('0','9');
$randarr = array_rand($randarr,$count);
$difference= array_diff($randarr,$arr); //let $arr be your array
if(count($difference)==0)
{
//your display code
}
this enables you to create as many random numbers as the user selects.
Upvotes: 1