---
# System prepended metadata

title: 常用筆記

---

# 常用筆記
## array_map
#### non arrow function
```php=
$numbers = [10, 20, 30, 40, 50];
$sum = array_map(function ($it, $index) {
    print_r($it . ' ' . $index . "\n");
    return $it * 10;
}, $numbers, array_keys($numbers));
print_r("map sum:");
print_r($sum);
print_r("---" . "\n");

```

#### arrow function
```php=
$sum = array_map(
    fn ($it, $index) => $it * 10,
    $numbers,
    array_keys($numbers)
);
print_r("map with arrow function sum:");
print_r($sum);
print_r("---" . "\n");
```

## array_reduce
#### non arrow function
透過 use函數 將外部的$numbers傳進callback內,
即可在array_reduce內部獲取迭代的index
```php=
$numbers = [10, 20, 30, 40, 50];
$sum = array_reduce($numbers, function ($sum, $it) use ($numbers) {
    $index = array_search($it, $numbers);
    print_r($index . " " . $sum . " " . $it . "\n");
    return $sum + $it;
}, 0);
print_r('reduce sum:' . $sum . "\n"); //150

```

#### arrow function
透過 use函數 將外部的$numbers傳進callback內,
即可在array_reduce內部獲取迭代的index

```php=
$numbers = [10, 20, 30, 40, 50];
$sum2 = array_reduce($numbers, fn ($sum, $it) => $sum + $it, 0);
print_r('reduce sum:' . $sum . "\n"); //150
```