I'm trying to create $scenario['B'] and $scenario['C'] using $scenario['A'] as seed data. The desired final arrays are:
$scenario['A'] = [ 1, 2, 3, 4, 5, 6, 7, 8];
$scenario['B'] = [101, 102, 103, 104, 105, 106, 107, 108];
$scenario['C'] = [201, 202, 203, 204, 205, 206, 207, 208];
I have tried the following but get an error message: Notice: Undefined variable: value in test.php on line 32.
$scenario['A'] = range(1, 8);
foreach(['B' => 100, 'C' => 200] as $key => $value):
$scenario[$key] = array_map(function($element) {return $element + $value;}, $scenario['A']);
endforeach;
I have tried changing part of the array_map to be function($element, $value) but that results in a different error Warning: Missing argument 2 for... Why can't it see $value? How can this be modified so it works?
This works:
$scenario['A'] = range(1, 8);
foreach(['B' => 100, 'C' => 200] as $key => $value):
$constant_array = array_fill(0, sizeof($scenario['A']), $value);
$scenario[$key] = array_map(function($element, $constant) {return $element + $constant;}, $scenario['A'], $constant_array);
endforeach;
Per http://php.net/manual/en/function.array-map.php "The number of parameters that the callback function accepts should match the number of arrays passed to the array_map()". The reason function($element, $value) did not work was because only 1 array was being passed to the array_map(). It is necessary to make $constant_array that is the same size as the seed array, $scenario['A'], so that all elements in the seed array are affected by array_map().
But I like the answer provided by @Nigel Ren more.
function($element) use($value) {