Create an Array of Specific Length with Pre-filled Values
Last Updated :
28 Jun, 2024
Creating an array of a specific length with pre-filled values is a common task in many programming languages. This operation is useful for initializing arrays with default values, setting up initial states, or preparing data structures for further manipulation. These types of problem in PHP are used in initialization of Data Structures and memory allocation.
These are the following methods to create an array of specific length with pre-filled values:
Using the array_fill() function
In this method, we have used the array_fill() function in PHP which is used to create an array of some specific length and then fill it with a specified value. This is the most concise and reliable method to solve this particular problem. It uses the three common parameters i.e. Start Index, Length and Value.
Example: We are using an array_fill() function for creating an array of specific length with pre-filled values.
PHP
<?php
$myArray = array_fill(0, 5, "Hello");
print_r($myArray);
?>
OutputArray
(
[0] => Hello
[1] => Hello
[2] => Hello
[3] => Hello
[4] => Hello
)
Using for loop
In this method, we initialize an empty array using $myArray = array() and start a for loop that ensure the run $length times. Inside the loop, we use the $myArray[] = $value for the statement to append the value and at last, we use the print_r($myArray) to print the contents of the $myArray array.
Example: We are using a for loop for creating an array of specific length with pre-filled values.
PHP
<?php
$length = 5;
$value = 'hello';
$myArray = array();
for ($i = 0; $i < $length; $i++) {
$myArray[] = $value;
}
print_r($myArray);
?>
OutputArray
(
[0] => hello
[1] => hello
[2] => hello
[3] => hello
[4] => hello
)
Using the array_map() function
In this method, we use the array_map() function to fill the array with a specific value and then create an array of length 5 filled with the value "hello". At the end, we gently print the output of the filled array.
Example: We are using an array_map() function for creating an array of specific length with pre-filled values.
PHP
<?php
function fillArray($value, $index)
{
return $value;
}
$filledArray = array_map(
'fillArray',
array_fill(0, 5, 'hello'),
array_keys(array_fill(0, 5, null))
);
print_r($filledArray);
OutputArray
(
[0] => hello
[1] => hello
[2] => hello
[3] => hello
[4] => hello
)