Page 1 of 1

Cant stop this infinite loop

Posted: Mon Jan 17, 2011 9:19 pm
by radium32
This part of it, full code below... it is an infinite loop! :banghead:

Code: Select all

$index = 0; // missing ";"
while ($index < count($user_array)) {
$next_user = $user_array[$index];
if (valid_email($next_user['email'])) {
$user_array[$index]['password'] = create_passwd();
}
else {
#set the user_array entry to null, for later deletion.
$user_array[$index] = null;
}
$index;
}









<?php
function create_passwd() {
#creates random 8-char alphanumeric password

$length=8;
$list=array_merge(range('a','z'),range(0,9));
shuffle($list);
$passwd=substr(join($list),0,$length);

return $passwd;
}

function valid_email($email) {
#this function takes a string and checks it against a regular expression,
#to ensure it's a valid email address.
$good_email = "([a-zA-Z0-9]+@[a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]+)+"; // missing """
if (ereg($good_email, $email)) {
echo $email." is a valid email address.<br>";
return true;
}
else {
echo $email." is NOT a valid email address.<br>";
return false;
}
}

$user_array = array( array('email' => "judy_g@comcast.net", 'password' => ''),
array('email' => "george@blah", 'password' => ''),
array('email' => "m-miller@dept.inc.com", 'password' => ''),
array('email' => "*@aol.com", 'password' => ''),
array('email' => "nobody", 'password' => ''));

#filter array for invalid email entries
$index = 0; // missing ";"
while ($index < count($user_array)) {
$next_user = $user_array[$index];
if (valid_email($next_user['email'])) {
$user_array[$index]['password'] = create_passwd();
}
else {
#set the user_array entry to null, for later deletion.
$user_array[$index] = null;
}
$index;
}
//now delete all NULL entries
$user_array = array_filter($user_array);
?>

<pre><? // missing "<?"
print_r($user_array);
?>

Re: Cant stop this infinite loop

Posted: Mon Jan 17, 2011 10:07 pm
by requinix
radium32 wrote:This part of it, full code below... it is an infinite loop! :banghead:
Yep! It sure is!

Why? Because you never increment $index. It keeps the same value, so the while condition will never change: always true (infinite loop) or always false (code never executes).

Re: Cant stop this infinite loop

Posted: Mon Jan 17, 2011 10:49 pm
by radium32
tasairis wrote:
radium32 wrote:This part of it, full code below... it is an infinite loop! :banghead:
Yep! It sure is!

Why? Because you never increment $index. It keeps the same value, so the while condition will never change: always true (infinite loop) or always false (code never executes).

yes, how would i fix this??

Re: Cant stop this infinite loop

Posted: Tue Jan 18, 2011 2:06 am
by Peter Kelly
If you add $i++; this will increment the $i by 1 every time its run. Just looking I persume you meant to do this by putting $index; on the bottom line ? simply change that to $index++;