Which is faster: in_array() or a bunch of expressions in PHP?

Is it faster to do the following:

 if ($var != 'test1' && $var != 'test2' && $var != 'test3' && $var != 'test4') { ... }


 if (!in_array($var, array('test1', 'test2', 'test3', 'test4') { ... }

Is there a number of values at which point it's faster to do one or the other?

(In this case, the array used in the second option doesn't alreay exist.)


i'd strongly suggest just using in_array(), any speed difference would be negligible, but the readability of testing each variable separately is horrible.

just for fun here's a test i ran:

$array = array('test1', 'test2', 'test3', 'test4');
$var = 'test';
$iterations = 1000000;

$start = microtime(true);
for($i = 0; $i < $iterations; ++$i) {
    if ($var != 'test1' && $var != 'test2' && $var != 'test3' && $var != 'test4') {}
$end = microtime(true);

print "Time1: ". ($end - $start)."<br />";

$start2 = microtime(true);
for($i = 0; $i < $iterations; ++$i) {
    if (!in_array($var, $array) ) {}
$end2 = microtime(true);

print "Time2: ".($end2 - $start2)."<br />";

// Time1: 1.12536692619
// Time2: 1.57462596893

slightly trivial note to watch for, if $var is not set, method 1 takes much longer (depending on how many conditions you test)

Need Your Help

ViewModel not being passed back to controller in POST method

c# asp.net-mvc asp.net-mvc-4 asp.net-mvc-viewmodel

Simple problem, but I can't figure out what is missing. I have a simple ViewModel (it'll get bigger):

Need background image over another background image

html css background

I have not been successful in solving this so far, so i need help. What I am trying to do is have a background image fitting a tablet. Inside I have a table, as well as a top right logo, but now I am

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.