Merge x arrays with array_merge()

Viewed 34

since I've tried different things - like for/while-loops, I finally ended up here. What I'm trying to do is to merge different x arrays (from a form) into one array, so that I can count the answers. My code for merging actually looks like this:

foreach($_POST as $key =>$value){
  foreach ($value as $answer){
    echo $answer."<br />";
  }
  $tmp+=1;
  $data[$key] = $value;
}

$results = array_merge($data['q1'], $data['q2']);

I'd like to input the content of array_merge based on how many questions (q1, q2, ...) are in the form. So I tried this:

$array_loop = array();
for ($k = 1 ; $k < $tmp; $k++) {
  $array_loop.='$data["q' . $k . '"], ';
};

Of course, it's not working because it's an array so string conversion. Any hints?

1 Answers

you can use

$result = array_merge(...$array_loop);

to save multiple arrays into one array

Related