Help us understand the problem. What is going on with this article?

# PCスペック

• macOS Mojave
• 2.3 GHz Intel Core i5
• メモリ16GB

# 方法

• loop.phpとmap.phpとwalk.phpを用意
• 0から999999の100万の配列を用意し、累乗したものを入れ直す
• １０回ずつ実行し、平均を出す
```\$ php loop.php
```

のような形で実行し、処理速度を出す

# ソースコード

loop.php
```<?php

\$start = microtime(true);

foreach (\$arr = range(0, 999999) as \$key => \$value) {
\$arr[\$key] = \$value**2;
}

\$end = microtime(true) - \$start;
echo "{\$end} 秒";

```
map.php
```<?php

\$start = microtime(true);

\$arr = array_map(function(\$i){ return \$i**2;}, range(0,999999));

\$end = microtime(true) - \$start;
echo "{\$end} 秒";
```
walk.php
```<?php

\$start = microtime(true);

array_walk(\$arr = range(0, 999999), function(&\$i){ return \$i**2;});

\$end = microtime(true) - \$start;
echo "{\$end} 秒";
```

# 結果

loop map walk
1 0.06867098808 0.07462501526 0.1094799042
2 0.06750392914 0.07323098183 0.1181879044
3 0.06451797485 0.07551503181 0.1073791981
4 0.06446099281 0.08033800125 0.1189579964
5 0.06456112862 0.0758960247 0.1152040958
6 0.06685209274 0.07563400269 0.106719017
7 0.07046103477 0.07318592072 0.1079549789
8 0.06416606903 0.07384204865 0.1147558689
9 0.06298303604 0.07454109192 0.1074810028
10 0.0647149086 0.07654190063 0.1151940823
average 0.06588921547 0.07533500195 0.1121314049

# 所感

foreachが一番早いのか...という感想

# おまけ

for.php
```<?php

\$start = microtime(true);

for (\$i=0; \$i < 1000000; \$i++) {
\$arr[] = \$i ** 2;
}

\$end = microtime(true) - \$start;
echo "{\$end} 秒";
```

だいたい0.042~0.043秒くらい。

while.php
```<?php

\$start = microtime(true);

\$i = 0;
while (\$i < 1000000) {
\$arr[] = \$i ** 2;
\$i++;
}

\$end = microtime(true) - \$start;
echo "{\$end} 秒";
```

だいたい0.041~0.042秒くらい。

Why do not you register as a user and use Qiita more conveniently?
1. We will deliver articles that match you
By following users and tags, you can catch up information on technical fields that you are interested in as a whole
2. you can read useful information later efficiently
By "stocking" the articles you like, you can search right away