I have another question, before I was wondering about if vs switch, and it turns out switch was faster, now I am again asking, which is faster? for or foreach? I am using the following code on my site and the array I am using contains about 35 values. I tried a foreach, and it seemed alittle fast, but I couldn't really tell, and I dont wana just think its faster..here is the code I use

for($i = 0; $i <= $total_illegal; $i++){
		if(strpos(strtolower($_SERVER['REQUEST_URI']), $illegal[$i]) !== FALSE){
			log_suspect($illegal[$i]);
			$stop = 3;
		}
	}

If i used a foreach this is wat it would look like

	foreach($illegal as $variable => $value){
		if(strpos(strtolower($_SERVER['REQUEST_URI']), $illegal[$variable]) !== FALSE){
			log_suspect($illegal[$variable]);
			$stop = 3;
		}
	}

Which one operates faster or would most likely operate faster? because speed is a rather important thing atm,..

    The difference will be too minute to matter.

    Still, if you dont use $total_illegal elsewhere, and it costs you a count() to obtain it, then you might as well go with the foreach loop.

      Also, if you're array has only associative (i.e., text) keys, I don't think for() would work because you couldn't reference by number.

        this should be just what you are looking for:

        http://www.php.lt/benchmark/phpbench.php.

        Also, i'd personally say from experience the for loop would be quicker. With the foreach loop (foreach(x as n => y)), PHP has to generate a copy of the array to work on in memory, which, when working with larger arrays could well cause some performance issues.

        In PHP5 you can get around this by calling the foreach loop by refrence like so:

        foreach($x as $n => &$y) {
        
        }
        

        🙂

          jonno946 wrote:

          With the foreach loop PHP has to generate a copy of the array to work on in memory

          Uh, huuuuuh? I'm calling you out.

          <?php
          $big_array = range(0,5000000);
          echo 'Got Big?';
          sleep(15);
          echo 'Getting Bigger?';
          $t=0;
          foreach($big_array as $k=>$v)
          {
          $t+=$v;
          }
          ?>

          Watch your total memory consumption when you run this. Where's the extra copy foreach() makes?

          for() for indexed arrays, foreach() for associative arrays; different semantics, different uses, different occasions for use. Use whichever is appropriate.

            Write a Reply...