简体   繁体   中英

Create new array from existing array php

Hi guys need help with foreach loop, I need to create array, called a with the items: [10, 3, 45, 98, 4, 7, 56, 23, 3, 1] . And then use a for-each loop to sum each item with 10 and put them in a new array called b .

Check code below it work on the same $a array but how to put them in a new array?

$a = [10, 3, 45, 98, 4, 7, 56, 23, 3, 1];
$b = [];

foreach ($a as &$value) {
    $value = 10 + $value;
}
echo $a; 

You need to assign sum to each key in new array.

$a = [10, 3, 45, 98, 4, 7, 56, 23, 3, 1];
$b = [];

foreach ($a as $key => $value) {
    $b[$key] = 10 + $value;
}

var_dump($b); // prints $b

See https://3v4l.org/bURiM .

This will also work if you will use $a as associative array:

$a = ['a' => 10, 'b' => 3, 'c' => 45];
$b = [];

foreach ($a as $key => $value) {
    $b[$key] = 10 + $value;
}

var_dump($b); // prints $b

See https://3v4l.org/UOBok .

通过对输入数组的所有元素执行相同的操作来生成新数组的过程称为mapping ,这也可以使用PHP中的高阶函数来完成,除非出于某些原因特别需要使用foreach循环。

$b = array_map(function($n) { return $n + 10; }, $a);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM