Scris pe

PHP: Foreach vs Array_walk

Azi va fac o comparatie intre 2 moduri de a parcurge un array in PHP – foreach vs array_walk. Care mod credeti ca e mai rapid? Aflati in video:

https://www.youtube.com/watch?v=_luoec2EYSE

Codul sursa pentru aceasta lectie:

<?php
$valoare = 0;

$arr = array_fill(0, 1000000, ['pret' => rand(), 'tva' => rand()]);

$start = microtime(true);
foreach ($arr as $item) {
  $valoare += $item['pret'] + $item['tva'];
}
$stop = microtime(true) - $start;
var_dump('foreach: '.$stop);

$start = microtime(true);
array_walk($arr, function($item, $key) use(&$valoare) {
    $valoare += $item['pret'] + $item['tva'];
});
$stop = microtime(true) - $start;
var_dump('array_walk: '.$stop);

echo $valoare;

 

Lasă un răspuns

Adresa ta de email nu va fi publicată. Câmpurile obligatorii sunt marcate cu *

Acest site folosește Akismet pentru a reduce spamul. Află cum sunt procesate datele comentariilor tale.

To respond on your own website, enter the URL of your response which should contain a link to this post's permalink URL. Your response will then appear (possibly after moderation) on this page. Want to update or remove your response? Update or delete your post and re-enter your post's URL again. (Find out more about Webmentions.)

Copyright © 2025 toate drepturile
nu sunt
rezervate. Faceti ce vreti, e o tara libera.
Cred ca nu mai are rost sa zic, dar tema e facuta de mine cu Tailwind CSS. Gasesti codul sursa aici.
Inca folosesc WordpPess 🧡. Tema e insa custom Laravel 😎.