I read this post: faster than in_array? but I tried an experiment with a part of my php code. In my site's database users have stored a string ($UserString here) of comma-separated text substrings. I originally was checking if a user input ($PostedVar) was a member of the array created by exploding $UserString by using a foreach loop (I have recreated a small part of the relevant code here):
$PostedVar = mysqli_real_escape_string($_POST['userinput']);
$CommaCount = substr_count($UserString, ',');
$ExplodedUserString = explode(",", $UserString);
$Break = 'nobreak';
$i = 1;
foreach ($ExplodedUserString as $EUS) {
$Current = $EUS;
if ($i > $CommaCount) {
break;
}
else if ($Current === $PostedVar) {
$Break = 'break';
break;
}
else {
$i++;
}
}//End foreach
if ($Break === 'break') {
echo "<script>
alert ('You have previously selected "'.$PostedVar.'". Please try again!');
location = 'home.php';
</script>"
}
else {
echo "<script>
alert ('Thanks for selecting "'.$PostedVar.'"!');
location = 'home.php';
</script>";
}
I then compared foreach vs. in_array to check $UserString by doing everything exactly the same except adding 2 microtime statements as follows for both foreach and in_array:
//foreach method
$time1 = microtime();
$i = 1;
foreach ($ExplodedUserString as $EUS) {
$Current = $EUS;
if ($i > $CommaCount) {
break;
}
else if ($Current === $PostedVar) {
$Break = 'break';
break;
}
else {
$i++;
}
}//End foreach
$time2 = microtime();
$Diff = $time2 - $time1;
if ($Break === 'break') {
echo "<script>
alert ('$Diff');
location = 'home.php';
</script>"
}
else {
echo "<script>
alert ('$Diff');
location = 'home.php';
</script>";
}
versus:
//in_array method
$time1 = microtime();
if (in_array($PostedVar, $ExplodedUserString)) {
$Break = 'break';
}
$time2 = microtime();
$Diff = $time2 - $time1;
if ($Break === 'break') {
echo "<script>
alert ('$Diff');
location = 'home.php';
</script>"
}
else {
echo "<script>
alert ('$Diff');
location = 'home.php';
</script>";
}
I did 9 trials where all factors were kept constant (clicked same submit button, same user, same $UserString, etc.) and threw out the high and low values...the mean of $Diff with 7 trials for both foreach and in_array was actually faster by 12% for in_array. Keep in mind this is for a short string of only 5 comma-separated values for $UserString. Especially for larger strings, wouldn't in_array be faster than a foreach loop? The importance for my site is that I anticipate typical $UserString values to have at least 10-20 times more characters than the $UserString I used to test.