Skip to content

Instantly share code, notes, and snippets.

@zualex
Created March 26, 2021 07:54
Show Gist options
  • Save zualex/0d101fb8b48701352117cfc253be2762 to your computer and use it in GitHub Desktop.
Save zualex/0d101fb8b48701352117cfc253be2762 to your computer and use it in GitHub Desktop.
foreach in loop
<?php
function printMemory($start, $header) {
printf(
"%s - Time: %s | Memory (current): %s KB | Memory (max): %s KB" . PHP_EOL,
$header,
number_format(round((microtime(true) - $start) * 1000, 6), 6, ',', ''),
number_format(round((memory_get_usage() / 1024), 2), 2, ',', ''),
number_format(round((memory_get_peak_usage() / 1024), 2), 2, ',', '')
);
}
$countProducts = 500;
$countTags = 1;
$products = [];
for($i = 1; $i <= $countProducts; $i++) {
$tags = [];
for($n = 1; $n <= $countTags; $n++) {
$tags['tag_' . $i . '_' . $n] = 'tag_' . $i . '_' . $n;
}
$products[] = [
'id' => $i,
'tags' => $tags,
];
}
$start = microtime(true);
$tags = [];
foreach($products as $product) {
foreach($product['tags'] as $tag) {
$tags[] = $tag;
}
}
printMemory($start, 'foreach in loop');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment