Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Note that as RoBorg pointed out, there's overhead in creating the array so it should be moved inside the iteration loop. For this reason, Sparr's post is also a little misleading as there's overhead with the array_flip function.</p> <p>Here's another example with all 5 variations:</p> <pre><code>$array = array('test1', 'test2', 'test3', 'test4'); $var = 'test'; $iterations = 1000000; $start = microtime(true); for($i = 0; $i &lt; $iterations; ++$i) { if ($var != 'test1' &amp;&amp; $var != 'test2' &amp;&amp; $var != 'test3' &amp;&amp; $var != 'test4') {} } print "Time1: ". (microtime(true) - $start); $start = microtime(true); for($i = 0; $i &lt; $iterations; ++$i) { if (!in_array($var, $array) ) {} } print "Time2: ".(microtime(true) - $start); $start = microtime(true); for($i = 0; $i &lt; $iterations; ++$i) { if (!in_array($var, array('test1', 'test2', 'test3', 'test4')) ) {} } print "Time2a: ".(microtime(true) - $start); $array2 = array_flip($array); $start = microtime(true); for($i = 0; $i &lt; $iterations; ++$i) { if (!isset($array2[$var])) {} } print "Time3: ".(microtime(true) - $start); $start = microtime(true); for($i = 0; $i &lt; $iterations; ++$i) { $array2 = array_flip($array); if (!isset($array2[$var])) {} } print "Time3a: ".(microtime(true) - $start); </code></pre> <p>My results:</p> <pre><code>Time1 : 0.59490108493 // straight comparison Time2 : 0.83790588378 // array() outside loop - not accurate Time2a: 2.16737604141 // array() inside loop Time3 : 0.16908097267 // array_flip outside loop - not accurate Time3a: 1.57209014893 // array_flip inside loop </code></pre> <p>In summary, using <code>array_flip</code> (with isset) is faster than inarray but not as fast as a straight comparison.</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