PHP - Check variable or compare string?

hortonindigo

New Member
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:\[code\]<?phpfunction 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);?>\[/code\]Excerpt 2 - Compare string:\[code\]<?phpfunction 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);?>\[/code\]I know we could simply use \[code\]in_array()\[/code\], 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!
 
Back
Top