vampke Posted January 8, 2008 Share Posted January 8, 2008 Hello, How can i compare two sets of variables with a for loop? basically I have a set of results stored as $result1, $result2, ... up to 5 and a set of $unumber1... to 5 what i want to do is for($i=1; $i <= 5; $i++) { for($j=1; $j <= 5; $j++) { if ($result.$j == $unumber.$i) { $correct++; } } } now the $result.$j is not the correct syntax can anyone give me a pointer on this? google was no help, i can only seem to find very basic for loops (allthough i thought this was one as well ) Quote Link to comment https://forums.phpfreaks.com/topic/85040-solved-for-loop-to-cycle-through-variables/ Share on other sites More sharing options...
kenrbnsn Posted January 8, 2008 Share Posted January 8, 2008 You want to use variable variables, although it would be far easier if you used arrays: <?php for($i=1; $i <= 5; $i++) { for($j=1; $j <= 5; $j++) { if ($result[$j] == $unumber[$i]) { $correct++; } } } ?> Here's some code using the variable variables: <?php for ($i=1; $i <=5; $i++) { ${'result'.$i} = rand(1,5); ${'unumber'.$i} = rand(1,5); } $correct = 0; for($i=1; $i <= 5; $i++) { for($j=1; $j <= 5; $j++) { if (${'result'.$j} == ${'unumber'.$i}) { $correct++; } } } echo $correct . "\n"; ?> Ken Quote Link to comment https://forums.phpfreaks.com/topic/85040-solved-for-loop-to-cycle-through-variables/#findComment-433683 Share on other sites More sharing options...
vampke Posted January 8, 2008 Author Share Posted January 8, 2008 thanks man, i'll look into the array stuff as well Quote Link to comment https://forums.phpfreaks.com/topic/85040-solved-for-loop-to-cycle-through-variables/#findComment-433827 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.