Link to home
Start Free TrialLog in
Avatar of EMB01
EMB01Flag for United States of America

asked on

PHP Programming Problem

I have a randomly assigned variable named $rand. I also have a set variable named $db. If $rand eqauls $db, I would like the script below to regenerate $rand up to seven times before displaying the "Stopped trying error." Why won't this code work? Attached is the code:
$rand = rand(100000, 999999);
$db = 5555555;
if ($rand != $db) { 
	echo $rand;
} else {
	for ($counter = 1; $counter < 7; $counter++) {
	$rand = rand(100000, 999999);
	if ($rand != $db) {
		echo $rand;
		} else { 
		echo "Random number could not be generated. Still trying... ";
		if ($counter == 7) {
		echo "Stopped trying."; }
	}
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of glcummins
glcummins
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of EMB01

ASKER

Thanks, didn't see that - one problem remains though - when I take control of both variables to test the for function, it seems it doesn't echo the "Stopped trying" text. Why is this?
<?php
$rand = 555555;
$db = 5555555;
if ($rand != $db)
{ 
	echo $rand;
}
else
{
	for ($counter = 1; $counter < 7; $counter++)
	{
		$rand = 555555;
		if ($rand != $db)
		{
			echo $rand;
		}
		else
		{ 
			echo "Random number could not be generated. Still trying...\n ";
			if ($counter == 7)
			{
				echo "Stopped trying.\n";
			}
		}
	}
}
?>

Open in new window

$counter will never equal 7 based on your for() statement. The loop only executes for $counter = 1 through $counter = 6. Less than seven will never equal seven.
Avatar of EMB01

ASKER

Well, I thought that, too. Then I tried 6 and it didn't work either.
$rand and $db also have to be equal. That block will never execute if they are unequal.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of EMB01

ASKER

Thanks for your help.