Open In App

How to Create an Array of Given Size in PHP?

This article will show you how to create an array of given size in PHP. PHP arrays are versatile data structures that can hold multiple values. Sometimes, it's necessary to create an array of a specific size, either filled with default values or left empty.

Create an Array of Given Size using array_fill() Function

The array_fill() function is a basic method to create an array of a specified size, filled with a given value.

<?php

function createArray($size, $value) {
    return array_fill(0, $size, $value);
}

// Driver code
$size = 5;
$value = 'Geeks';
$array = createArray($size, $value);

print_r($array);

?>

Output
Array
(
    [0] => Geeks
    [1] => Geeks
    [2] => Geeks
    [3] => Geeks
    [4] => Geeks
)

Explanation:

Create an Array of Given Size using range() and array_map() Functions

For creating an array of a given size with default values, you can use a combination of range() and array_map() functions.

<?php

function createArray($size, $value) {
    return array_map(function() use (
        $value) { return $value; }, 
        range(1, $size)
    );
}

// Driver code
$size = 5;
$value = 'Geeks';
$array = createArray($size, $value);

print_r($array);

?>

Output
Array
(
    [0] => Geeks
    [1] => Geeks
    [2] => Geeks
    [3] => Geeks
    [4] => Geeks
)

Explanation:

Create an Array of Given Size using a Loop

You can also use a loop to create an array of a given size, manually adding elements until the array reaches the desired length.

<?php

function createArray($size, $value) {
    $array = [];
    for ($i = 0; $i < $size; $i++) {
        $array[] = $value;
    }
    return $array;
}

// Driver code
$size = 5;
$value = 'Geeks';
$array = createArray($size, $value);

print_r($array);

?>

Output
Array
(
    [0] => Geeks
    [1] => Geeks
    [2] => Geeks
    [3] => Geeks
    [4] => Geeks
)

Explanation:

Article Tags :