2009-07-16 49 views

回答

0

我在這裏添加了一個遲到的答案,因爲我認爲如果人們使用多個數組檢查,我有更好的解決方案。

如果你只是檢查一個數組,然後使用PHP的is_array()做這項工作就好了。

if (is_array($users)) { 
    is an array 
} else { 
    is not an array 
} 

但是,如果您正在檢查多個陣列 - 在例如環 - 再有就是這個一個更好的表演方案,使用強制:

if ((array) $users !== $users) { 
    // is not an array 
} else { 
    // is an array 
} 

證明

如果你運行這個性能測試,你會看到相當的性能差異:

<?php 

$count = 1000000; 

$test = array('im', 'an', 'array'); 
$test2 = 'im not an array'; 
$test3 = (object) array('im' => 'not', 'going' => 'to be', 'an' => 'array'); 
$test4 = 42; 
// Set this now so the first for loop doesn't do the extra work. 
$i = $start_time = $end_time = 0; 

$start_time = microtime(true); 
for ($i = 0; $i < $count; $i++) { 
    if (!is_array($test) || is_array($test2) || is_array($test3) || is_array($test4)) { 
     echo 'error'; 
     break; 
    } 
} 
$end_time = microtime(true); 
echo 'is_array : '.($end_time - $start_time)."\n"; 

$start_time = microtime(true); 
for ($i = 0; $i < $count; $i++) { 
    if (!(array) $test === $test || (array) $test2 === $test2 || (array) $test3 === $test3 || (array) $test4 === $test4) { 
     echo 'error'; 
     break; 
    } 
} 
$end_time = microtime(true); 
echo 'cast, === : '.($end_time - $start_time)."\n"; 

echo "\nTested $count iterations." 

?> 

結果

is_array : 7.9920151233673 
cast, === : 1.8978719711304 
+0

對不起,但我會堅持`is_array`。 **它非常精確地描述了它的作用。**在單次調用中保存的幾微秒不值得源代碼混淆。如果你在半年內再次看到這些代碼,你會在這裏試圖做的WTF。 – deceze 2014-07-25 15:57:40