Skip to content

Instantly share code, notes, and snippets.

@Nathan-Wall
Last active August 29, 2015 14:01
Show Gist options
  • Save Nathan-Wall/aaff656f6106835a616b to your computer and use it in GitHub Desktop.
Save Nathan-Wall/aaff656f6106835a616b to your computer and use it in GitHub Desktop.
PHP `for`s
<?php
$elements = array();
////
// An array of 10,000 elements with random string values
////
for($i = 0; $i < 10000; $i++) {
$elements[] = (string)rand(10000000, 99999999);
}
$time_start = microtime(true);
$el = null;
////
// for test
////
$numb = count($elements);
for($i = 0; $i < $numb; $i++) {
$el = $elements[$i];
}
$time_end = microtime(true);
$for_time = $time_end - $time_start;
$time_start = microtime(true);
////
// for with count() inside loop test
////
for($i = 0; $i < count($elements); $i++) {
$el = $elements[$i];
}
$time_end = microtime(true);
$for_count_time = $time_end - $time_start;
$time_start = microtime(true);
////
// foreach test
////
foreach($elements as $element) {
$el = $element;
}
$time_end = microtime(true);
$foreach_time = $time_end - $time_start;
echo "For took: " . number_format($for_time * 1000, 3) . "ms\n";
echo "For with count() took: " . number_format($for_count_time * 1000, 3) . "ms\n";
echo "Foreach took: " . number_format($foreach_time * 1000, 3) . "ms\n";
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment