How to use array_fill() and array_map() Functions In PHP
We can use the array_fill() function to create an array filled with a placeholder value and then use array_map() to replace each placeholder with the appropriate number.
Example: In this method, array_fill(0, $n, null) creates an array of length $n filled with null values. array_keys() retrieves the keys of this array (0 to $n-1), and array_map() is used to increment each key by 1, resulting in an array of numbers from 1 to $n.
<?php
// Create array of Given Range
function createArr($n) {
return array_map(function($value) { return $value + 1; },
array_keys(array_fill(0, $n, null)));
return $arr;
}
// Driver code
$n = 10;
$arr = createArr($n);
print_r($arr);
?>
Output
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 [7] => 8 [8] => 9 [9] => 10 )
Create an array containing 1…N numbers in PHP
Given an element N, the task is to create an array containing numbers from 1 to N in PHP. There are multiple ways to generate a list of numbers for iteration, manipulation, or display.
Below are the approaches to create an array containing 1….N numbers in PHP:
Table of Content
- Using range() Function
- Using for Loop
- Using array_fill() and array_map() Functions