Home > Software design >  Populating associative array values from other arrays in PHP
Populating associative array values from other arrays in PHP

Time:05-06

If I have separate arrays w/ values for "questions" and "answers" like so:

var_dump($questions)

array (size=2)
  0 => string 'Question 1' (length=10)
  1 => string 'Question 2' (length=10)

var_dump($answers)

array (size=2)
  0 => string 'Answer 1' (length=10)
  1 => string 'Answer 2' (length=10)

How can I use these arrays to populate the values of a "master" associative array w/ keys for "question" and "answer" so I can then use a foreach loop to easily output the question/answer pairs? I'm trying to loop over each of the $questions and $answers arrays to populate values of a $results array- I've tried

foreach ( $questions as $question ) {
    $results[] = ['question' => $question];
}

and this creates separate items for each question, but I'm not sure how to add the "answer" values into the same array items to create the pairs. Thank you for any assistance here.

CodePudding user response:

Not sure I'm understanding the question correctly, but the array_combine() function may do what you want.

$master = array_combine($questions, $answers);

This will give you:

[
    'question 1' => 'answer 1',
    'question 2' => 'answer 2',
    'question 3' => 'answer 3',
]

Then you can do:

foreach ($master as $question => $answer) {
    ...
}

Note, this implies that questions are unique.

If instead, you want an indexed array of associative arrays, you could do something like:

$master = [];
foreach (array_combine($questions, $answers) as $question => $answer) {
    $master[] = [
        'question' => $question,
        'answer' => $answer,
    ];
}

This will give you:

[
    [
        'question' => 'question 1',
        'answer' => 'answer 1',
    ],
    [
        'question' => 'question 2',
        'answer' => 'answer 2',
    ],
    [
        'question' => 'question 3',
        'answer' => 'answer 3',
    ],
]

Or, more traditionally:

$master = [];
for ($i = 0; $i < count($questions); $i  ) {
    $master[] = [
        'question' => $questions[$i],
        'answer' => $answers[$i],
    ]
}
  • Related