How to use array_map() and range() Functions In PHP
The combination of array_map() and range() can create a zero-filled array.
- range(1, $length) generates an array of integers from 1 to $length.
- array_map() applies a callback function that returns 0 for each element in the range array, resulting in a zero-filled array.
Example: This example shows the use of array_map() and range() function to create zero filled array.
<?php
function zeroFilledArr($len) {
return array_map(function() {
return 0;
}, range(1, $len));
}
// Driver code
$len = 5;
$arr = zeroFilledArr($len);
print_r($arr);
?>
Output
Array ( [0] => 0 [1] => 0 [2] => 0 [3] => 0 [4] => 0 )
Creating a Zero-Filled Array in PHP
Creating an array filled with zeros can be useful in various scenarios, such as initializing an array for further manipulation or setting up a default state. This article explores multiple approaches to creating a zero-filled array in PHP. A zero-filled array is an array where each element is initialized to zero. This can be achieved using different PHP functions and methods.
These are the following methods:
Table of Content
- Using array_fill() Function
- Using a for Loop
- Using array_map() and range() Functions
- Using array_pad() Function