由于我经常处理大型数据集,所以我会选择isset
or !empty
在关联数组上并检查键,就像 @Barmar 建议的那样。这是一个快速 1M 基准测试英特尔® 酷睿™ i3-540 (3.06 GHz)
$test = array("read", "edit", "delete", "admin");
echo "<pre>";
// --- strpos($rights,$test[$i%4]) ---
$rights = 'read,edit,delete,admin';
$mctime = microtime(true);
for($i=0; $i<=1000000; $i++) { if (strpos($rights,$test[$i%4]) !== false) { }}
echo ' strpos(... '.round(microtime(true)-$mctime,3)."s\n";
// --- in_array($test[$i%4],$rights) ---
$rights = array("read", "edit", "delete", "admin");
$mctime = microtime(true);
for($i=0; $i<=1000000; $i++) { if (in_array($test[$i%4],$rights)) { }}
echo 'in_array(... '.round(microtime(true)-$mctime,3)."s\n";
// --- !empty($rights[$test[$i%4]]) ---
$rights = array('read' => 1, 'edit' => 1, 'delete' => 1, 'admin' => 1);
$mctime = microtime(true);
for($i=0; $i<=1000000; $i++) { if (!empty($rights[$test[$i%4]])) { }}
echo ' !empty(... '.round(microtime(true)-$mctime,3)."s\n";
// --- isset($rights[$test[$i%4]]) ---
$rights = array('read' => 1, 'edit' => 1, 'delete' => 1, 'admin' => 1);
$mctime = microtime(true);
for($i=0; $i<=1000000; $i++) { if (isset($rights[$test[$i%4]])) { }}
echo ' isset(... '.round(microtime(true)-$mctime,3)."s\n\n";
echo "</pre>";
获胜者是isset
:
strpos(... 0.393s
in_array(... 0.519s
!empty(... 0.232s
isset(... 0.209s