Current Location: Home> Latest Articles> Can array_fill() be used to fill a boolean value?

Can array_fill() be used to fill a boolean value?

M66 2025-06-05

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.

Syntax Introduction

 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.

Fill boolean values ​​with array_fill()

Let's see how to use it to create an array of boolean types.

Example: Filled to true

 <?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 .

Example: Fill as false

 <?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 .

Is it possible to use array_fill() to create a boolean array?

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 .

Practical scenarios

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.

Tips

  • 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)
}

Summarize

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.