Jump to content

Recommended Posts

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  :))

 

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.