Hi,
I wonder which of these excerpts should take less resources, when we want to see if "word" is an element of an array:
Excerpt 1 - Check variable:
<?php
function checkWord($word, $elements) {
$array = array($word => true);
foreach ($elements as $element) {
if (isset($array[$element])) return true;
}
return false;
}
$elements = array('this', 'is', 'an', 'array', 'with', 'a', 'word');
checkWord('word', $elements);
?>
Excerpt 2 - Compare string:
<?php
function checkWord($word, $elements) {
foreach ($elements as $element) {
if ($element == $word) return true;
}
return false;
}
$elements = array('this', 'is', 'an', 'array', 'with', 'a', 'word');
checkWord('word', $elements);
?>
I know we could simply use in_array()
, but it would only work for this case.
The question here is for when we have to explode lines of a file, or any other situation that we don't have the $element so easily.
So, resuming, is a variable check better than comparing strings?
EDIT Please understand that I know there are better ways of doing this. I am just asking which of the ways above is better and takes less resources. I assume that checking variables do not compare strings and it's instant, while comparing string should be slower. Am I correct?
Thank you!