当我们想知道“word”是否是数组的一个元素时,我想知道这些摘录中哪一个应该占用更少的资源:
摘录1-检查变量:
<?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);
?>
<?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);
?>
我知道我们可以用
in_array()
,但这不是重点。
总之,使用isset进行变量检查比比较字符串好吗?
我知道
有更好的方法。我是
只是