Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Arckays's avatar

Triple foreach in a table

Hi people.

I'm doing a website, and in this site, there is a multiple form that return me three arrays. Each of these array give me an id that I'll use in my database for getting a dimension.

So now I want to have an array for doing this request, but i'm stuck with this.

Actually I'm trying with three foreach and putting it in the table :

$dimension = [];

        foreach ($hauteurs_av as $hts => $ht)
        {
            $dimension[] = [
                'hauteur' => $ht
            ];
        }
        foreach ($largeurs_av as $lrg => $lg)
        {
            $dimension[] = [
                'largeur' => $lg
            ];
        }
        foreach ($diametre_av as $dmt => $dm)
        {
            $dimension[] = [
                'diametre' => $dm
            ];
        }

But it return me 6 arrays. What I want is an array like :

array:2 [▼
  0 => array:1 [▼
    "hauteur" => "17"
    "largeur" => "108"
    "diametre" => "16"  
  ]
  1 => array:1 [▼
    "hauteur" => "17"
    "largeur" => "108"
    "diametre" => "16"  
  ]
]

Do you have an idea about how I could have this array ? Thank you !

0 likes
2 replies
tykus's avatar
tykus
Best Answer
Level 104

Option 1: Loop

$result = [];

// iterate over one of the arrays, and expect the others to have same number of elements:
foreach($hauteurs_av as $index => $hauteur) { 
    $result[] = [
        'hauteur' => $hauteur,
        'largeur' => $largeurs_av[$index],
        'diametre' => $diametre_av[$index] 
    ];
}
tykus's avatar

Option 2: Collection pipeline transposition

$result = collect([$hauteur_av, $largeurs_av, $diametre_av])
    ->transpose()
    ->map(function ($data) {
        return [
            'hauteur' => $data[0],
            'largeur' => $data[1],
            'diametre' => $data[2],
        ];
    })->toArray();

transpose() doesn't exist as a Collection method, but you can macro it in a ServiceProvider:

Collection::macro('transpose', function () {
    $items = array_map(function (...$items) {
        return $items;
    }, ...$this->values());

    return new static($items);
});

credit: https://adamwathan.me/2016/04/06/cleaning-up-form-input-with-transpose/

Please or to participate in this conversation.