I've found a faster way of determining an array. If you use is_array() millions of times, you will notice a *huge* difference. On my machine, this method takes about 1/4 the time of using is_array().
Cast the value to an array, then check (using ===) if it is identical to the original.
<?php
if ( (array) $unknown === $unknown ) {
echo '$unknown is an array';
} else {
echo '$unknown is not an array';
}
?>
You can use this script to test the speed of both methods.
<pre>
What's faster for determining arrays?
<?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."
?>
</pre>
Prints something like:
What's faster for determining arrays?
is_array : 7.9920151233673
cast, === : 1.8978719711304
Tested 1000000 iterations.
----
Server IP: 69.147.83.197
Probable Submitter: 65.44.194.66
----
Manual Page -- http://www.php.net/manual/en/function.is-array.php
Edit -- https://master.php.net/note/edit/98156
Del: integrated -- https://master.php.net/note/delete/98156/integrated
Del: useless -- https://master.php.net/note/delete/98156/useless
Del: bad code -- https://master.php.net/note/delete/98156/bad+code
Del: spam -- https://master.php.net/note/delete/98156/spam
Del: non-english -- https://master.php.net/note/delete/98156/non-english
Del: in docs -- https://master.php.net/note/delete/98156/in+docs
Del: other reasons-- https://master.php.net/note/delete/98156
Reject -- https://master.php.net/note/reject/98156
Search -- https://master.php.net/manage/user-notes.php
lmpx.com only provides a reader for public news (NNTP) servers. It is not
affiliated with the servers or forums shown here and is not responsible for
the content of articles, which is written by their respective authors.