1

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.

1
  • You probably need function($element) use($value) { Commented Dec 16, 2017 at 17:07

1 Answer 1

2

You need to add the use to your function call...

$scenario['A'] = range(1, 8);
foreach(['B' => 100, 'C' => 200] as $key => $value):
    $scenario[$key] = array_map(function($element) use ($value) 
            {return $element + $value;}, $scenario['A']);
endforeach;
print_r($scenario['B']);

Gives...

Array
(
    [0] => 101
    [1] => 102
    [2] => 103
    [3] => 104
    [4] => 105
    [5] => 106
    [6] => 107
    [7] => 108
)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.