Tag Archives: testing

Small testing for array_combine in PHP4

One of mine bbPress plugin is not compatible with PHP4. It uses array_combine. There are few suggestions from comments, but it’s hard to pick one without information. Therefore I did a quick test, which is for execution speed.

<?php
$start = microtime();
define('RAND_MAX', mt_getrandmax());
$key = array();
for ($i=0; $i<5000; $i++)
    $key&#91;&#93; = 'key' . mt_rand(0, RAND_MAX);

$value = array();
for ($i=0; $i<5000; $i++)
    $value&#91;&#93; = 'value' . mt_rand(0, RAND_MAX);
// http://www.php.net/manual/en/function.array-combine.php#78244
function array_combine1($arr1,$arr2) {
    $out = array();
    foreach($arr1 as $key1 => $value1)
        $out[$value1] = $arr2[$key1];
    return $out;
    }
// http://www.php.net/manual/en/function.array-combine.php#77231
function array_combine2($keys, $values) {
    $result = array();
    foreach(array_map(null, $keys, $values) as $pair)
        $result[$pair[0]]=$pair[1];
    return $result;
    }
// http://www.php.net/manual/en/function.array-combine.php#76994
function array_combine3($keys, $values) {
    $result = array() ;
    while( ($k=each($keys)) && ($v=each($values)) ) $result[$k[1]] = $v[1] ;
    return $result ;
    }
// http://www.php.net/manual/en/function.array-combine.php#74412
function array_combine4($a1,$a2) {
    for($i=0;$i<count($a1);$i++)
        $ra&#91;$a1&#91;$i&#93;&#93; = $a2&#91;$i&#93;;
    if(isset($ra)) return $ra; else return false;
    }

echo microtime() - $start, "\n";

$start = microtime();
$kv = array_combine($key, $value);
echo microtime() - $start, "\n";

$start = microtime();
$kv1 = array_combine1($key, $value);
echo microtime() - $start, '|', $kv == $kv1, "\n";
unset($kv1);

$start = microtime();
$kv2 = array_combine2($key, $value);
echo microtime() - $start, '|', $kv == $kv2, "\n";
unset($kv2);

$start = microtime();
$kv3 = array_combine3($key, $value);
echo microtime() - $start, '|', $kv == $kv3, "\n";
unset($kv3);

$start = microtime();
$kv4 = array_combine4($key, $value);
echo microtime() - $start, '|', $kv == $kv4, "\n";
unset($kv4);
?>

Result is (tested in PHP 5.2.4, not quite a useful testing since should be tested in PHP 4):

0.03834
0.001877
0.005486|1
0.018785|1
0.037229|1
0.015718|1

Obviously, first one is the winner. It should also use less memory footprint, since the code is simpler than others (no additional function calls or double indexing).

Design a site like this with WordPress.com
Get started