[lang-ref] ( init_array_with_size ) ( php )
<?php
public function testInitArrayWithSize(): void
{
// array_fill(0, n, x)
$items = array_fill(0, 3, 'Camera!');
$this->assertIsArray($items);
$this->assertSame(['Camera!', 'Camera!', 'Camera!'], $items);
}
<?php
public function testInitArrayWithSizeAlternative(): void
{
// this is safe.
// PHP arrays use copy-on-write, so modifying one nested array does not affect the others.
$items = array_fill(0, 3, ['a', 'b']);
$this->assertSame([['a', 'b'], ['a', 'b'], ['a', 'b']], $items);
$items[0][] = 'c'; // this does not change other elements.
$this->assertSame([['a', 'b', 'c'], ['a', 'b'], ['a', 'b']], $items);
}