Search code examples
phparraysmultidimensional-arraygroupingtranspose

How to combine and transpose 2 PHP arrays


I have two simple PHP arrays, like so:

types = ['a', 'b', 'c'];      // 3x1 array
numbers = [1, 2, 3];          // 3x1

What I want is to restructure the data (i.e. transpose + combine them) to be able to loop through them, like this:

result = [['a', 1], ['b', 2], ['c', 3]];    // 3x2

Is there a smart way to achieve this in PHP with some array_XXX native function or do I have to loop over both to manually compose it? Thanks.


Solution

  • If the values in $types are unique, you can do this:

    $combined = array_combine($types, $numbers);
    

    This will yield:

    [
        'a' => 1,
        'b' => 2,
        'c' => 3,
    ]
    

    Which you can then iterate over with:

    foreach ($combined as $type => $number)
    

    Or just:

    foreach (array_combine($types, $numbers) as $type => $number)
    

    If the values in $types are not unique, you can do this:

    $combined = array_map(function($a, $b) { return [$a, $b]; }, $types, $numbers);