PHP iterable to array or Traversable

For php >= 7.4 this works pretty well out of the box:

$array = array(...$iterable);

See https://3v4l.org/L3JNH

Edit: Works only as long the iterable doesn't contain string keys


Not sure this is what are you searching for but this is the shortest way to do it.

$array = [];
array_push ($array, ...$iterable);

I'm not very sure why it works. Just I found your question interesting and I start fiddling with PHP

Full example:

<?php

function some_array(): iterable {
    return [1, 2, 3];
}

function some_generator(): iterable {
    yield 1;
    yield 2;
    yield 3;
}

function foo(iterable $iterable) {
    $array = [];
    array_push ($array, ...$iterable);
    var_dump($array);

}

foo(some_array());
foo(some_generator());

It would be nice if works with function array(), but because it is a language construct is a bit special. It also doesn't preserve keys in assoc arrays.