How long would it take for a For loop to run through 1000 loops?
I have a SELECT query that could return a 1000 names max - more likely to
return 300-400 names.
I would like to compare an input string to the names in the array returned
by the SELECT query.
I have two questions:
How long would a for loop take to run through (all the 1000 names in ) the
array to find if there is a matching value? AND
Is there a way to terminate the loop as soon as a match is found? (Suppose
a match is found on the 10th name, running through the rest would be a
waste. It doesn't matter if there are more matches - just hitting the
first one is enough for my purpose.)
I have tried return, and exit but both don't work exactly the way I'd like.
Here are the codes I am running to test the idea: The first php file
contains the array of names
<?php
$names=array("R","A","V");
$arrlengths=count($names);
?>
and is included in the second file.
<?php
include 'test-2nd-include.php';
//the above file contains an array with three names
//it also contains the length of the array in the arrlengths variable
//in the test case we are using a name assigned to a variable in this file
//however, when used on the registration page, it will be a value that has
come through $_POST
$rr = "A";
//a test variable that is initially = 0 but will be incremented if value
is found in array
$ohno = 0;
for($xx=0;$xx<$arrlengths;$xx++)
{
echo "$ names [ $xx ] ", $names[$xx];
echo "<br>";
if ($names[$xx] ==$rr) {
// if the value is found then the test variable is set t
$ohno = 1;
}
}
if ($ohno > 0){
echo " $rr already exists in our members list" ;
}
else {
echo "Congratulations! $rr is still available!" ;
}
?>
What I have seen is that if I use return or exit after $ohno = 1; the
messages at the end do not get processed. If I move the if ($ohno >
0){......$rr is still available!" ;} into the for loop the results are
really weird!
I am sure I am missing something but after staring at this for an entire
afternoon, I still cannot find a way to make the code stop running after
it encounters the first match AND display the appropriate messages - both
when it finds a match and when it doesn't.
And that is the reason for the first question! Is the time I am spending
trying to do this worth the saving in terms of server time/processing in
the long run? After all, with a max of 1000 expected users, this code
might run about 300-400 times over a period of a month or so?!?
No comments:
Post a Comment