Note that there are some explanatory texts on larger screens.

plurals
  1. POHow long would it take for a For loop to run through 1000 loops?
    text
    copied!<p>I have a SELECT query that could return a 1000 names max - more likely to return 300-400 names.</p> <p>I would like to compare an input string to the names in the array returned by the SELECT query. </p> <p>I have two questions:</p> <ol> <li>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</li> <li>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.)</li> </ol> <p>I have tried return, and exit but both don't work exactly the way I'd like. </p> <p>Here are the codes I am running to test the idea: The first php file contains the array of names </p> <pre><code>&lt;?php $names=array("R","A","V"); $arrlengths=count($names); ?&gt; </code></pre> <p>and is included in the second file.</p> <pre><code>&lt;?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&lt;$arrlengths;$xx++) { echo "$ names [ $xx ] ", $names[$xx]; echo "&lt;br&gt;"; if ($names[$xx] ==$rr) { // if the value is found then the test variable is set t $ohno = 1; } } if ($ohno &gt; 0){ echo " $rr already exists in our members list" ; } else { echo "Congratulations! $rr is still available!" ; } ?&gt; </code></pre> <p>What I have seen is that if I use return or exit after <code>$ohno = 1;</code> the messages at the end do not get processed. If I move the <code>if ($ohno &gt; 0){......$rr is still available!" ;}</code> into the for loop the results are really weird!</p> <p>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. </p> <p>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?!?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload