PHP use array_merge with N arrays

Viewed 69

I would like to group several (n) tables into a single large table. Exemple :

$tab1 = array("test0","test1");
$tab2 = array("test2","test3");
$tab3 = array("tes..","....");

But for example with 10 tables. Instead of writing

$result = array_merge($tab1, $tab2, $tab3 --> $tab10);

The algorithm should do this on its own, but I admit I'm lost. I thought I would do it recursively.

If anyone would have how to do it, thanks

4 Answers

I would start by not-using numerical variable names: Instead I use an array:

<?php
$tab[] = array("test0","test1");
$tab[] = array("test2","test3");
$tab[] = array("test4","test3");
?>

Next: you can loop through them to merge

<?php 
$result = array();
for($i=0;$i<count($tab);$i++) {
   $result = array_merge($result, $tab[i]);
 }  
 ?>

Using array_merge() with all of the arrays in one main array can be simplified using the argument unpacking (or splat operator) ......

$tab[] = array("test0","test1");
$tab[] = array("test2","test3");
$tab[] = array("test4","test3");

print_r(array_merge(...$tab));

One thing comes to mind, it's not the prettiest, but it works. Without changing your array names.

It checks for $$tab, which is basically a variable starting with 'tab' and ending with our incremented $i. Then it merges them one by one.

<?php

$tab1 = array("test0", "test1");
$tab2 = array("test2", "test3");
$tab3 = array("tes..", "....");

$i = 1;

$tab = 'tab' . $i;

$data = [];

while (isset($$tab)) {
    $data = array_merge($data, $$tab);
    $i++;
    $tab = 'tab' . $i;
}

print_r($data);

This is the output:

Array ( [0] => test0 [1] => test1 [2] => test2 [3] => test3 [4] => tes.. [5] => .... )

Don't introduce variables which you don't "use":

$tables = [];
$tables[] = ["test0", "test1"];
$tables[] = ["test2", "test3"];
$tables[] = ["tes..", "...."];
$mergedTables = [];
foreach ($tables as $table) {
    $mergedTables = array_merge($tables, $table);
}
Related