Skip to content

Instantly share code, notes, and snippets.

@nodesocket
Created October 17, 2012 23:53
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nodesocket/3909074 to your computer and use it in GitHub Desktop.
Save nodesocket/3909074 to your computer and use it in GitHub Desktop.
Benchmark of for vs foreach in PHP
<?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);
////
// for test
////
for($i = 0; $i < count($elements); $i++) { }
$time_end = microtime(true);
$for_time = $time_end - $time_start;
$time_start = microtime(true);
////
// foreach test
////
foreach($elements as $element) { }
$time_end = microtime(true);
$foreach_time = $time_end - $time_start;
echo "For took: " . number_format($for_time * 1000, 3) . "ms\n";
echo "Foreach took: " . number_format($foreach_time * 1000, 3) . "ms\n";
?>
@manoelhc
Copy link

manoelhc commented Feb 3, 2015

You can add "foreach($elements as $key => $element) { }" as well. It'll be the worst one.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment