In PHP, array_fill() is a very practical function that can be used to quickly create an array of specified lengths and fill each element with the same value. Although it is often used to fill in strings or numbers, you can also use it to fill in boolean values.
array_fill(int $start_index, int $count, mixed $value): array
$start_index : The value of the first index in the array.
$count : The number of elements to be filled.
$value : The value used to fill the array.
Let's see how to use it to create an array of boolean types.
<?php
$boolArray = array_fill(0, 5, true);
print_r($boolArray);
?>
Output:
Array
(
[0] => 1
[1] => 1
[2] => 1
[3] => 1
[4] => 1
)
Although it is shown as 1 in the print result, it is actually a boolean true , which PHP will be expressed as 1 when outputting the boolean true .
<?php
$boolArray = array_fill(0, 3, false);
print_r($boolArray);
?>
Output:
Array
(
[0] =>
[1] =>
[2] =>
)
false appears empty in the array, but that doesn't mean it has no value, it is indeed a boolean false .
The answer is yes . array_fill() does not limit the type of value you pass in, whether it is an integer, string, object, or boolean type, it can be used. That is, you can use it to create an array of boolean types, whether you need to populate true or false .
For example, you are building a boolean switch array and initializing a set of functional states:
<?php
$features = array_fill(0, 10, false); // initialization10One function is off
$features[2] = true; // Enable the3Features
print_r($features);
?>
This method is concise and clear, suitable for initializing the default state array.
You can use var_dump() to verify that the elements in the array are indeed boolean:
<?php
$flags = array_fill(0, 2, true);
var_dump($flags);
?>
Output:
array(2) {
[0]=>
bool(true)
[1]=>
bool(true)
}
array_fill() is a powerful tool for filling arrays. It not only supports numbers or strings, but also applies to boolean values. Whether you create an array of default values or a quick initialization state, you have the flexibility to use it.