Voting

: min(zero, eight)?
(Example: nine)

The Note You're Voting On

hperrin at gmail dot com
14 years ago
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 not an array';
} else {
echo
'$unknown is 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.

<< Back to user notes page

To Top