Jump to content

[SOLVED] for loop to cycle through variables


vampke

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.