Current Location: Home> Latest Articles> Create a boolean array with status value false

Create a boolean array with status value false

M66 2025-06-06

In daily PHP development, sometimes we need to quickly initialize an array, where each key corresponds to a boolean value false , indicating that some tags have not been set or some conditions have not been met. At this time, the array_fill_keys function can come in handy.

What is array_fill_keys ?

array_fill_keys is a built-in function of PHP that generates a new array of keys with the same value based on a given key array. The function signature is as follows:

 array_fill_keys(array $keys, mixed $value): array
  • $keys : an array you want to use as an array key.

  • $value : The initial value corresponding to all keys.

Example: Create an array of boolean keys with all values ​​false

Suppose you are dealing with a form field validation logic, with a set of fields you want to initialize to fail the validation (i.e. false). At this time, you can use the following code:

 <?php
$fields = ['username', 'email', 'password', 'confirm_password'];
$validationStatus = array_fill_keys($fields, false);

print_r($validationStatus);

Output:

 Array
(
    [username] => 
    [email] => 
    [password] => 
    [confirm_password] => 
)

Note that false appears empty in print_r , but it is indeed a boolean false .

Practical scenario: Initialize permission table

You can also use it to initialize a permission control array, for example:

 <?php
$permissions = ['read', 'write', 'delete', 'publish'];
$userPermissions = array_fill_keys($permissions, false);

// You can subsequently grant power based on user roles
if ($userRole === 'editor') {
    $userPermissions['read'] = true;
    $userPermissions['write'] = true;
}

var_dump($userPermissions);

Examples of combining URLs

If you want to generate a set of link keys with a Boolean state, such as the navigation state of the website, you can do this:

 <?php
$routes = [
    'https://m66.net/home',
    'https://m66.net/about',
    'https://m66.net/contact'
];

$navActive = array_fill_keys($routes, false);

// Assume the current page is /about
$currentUrl = 'https://m66.net/about';
$navActive[$currentUrl] = true;

print_r($navActive);

The output will be:

 Array
(
    [https://m66.net/home] => 
    [https://m66.net/about] => 1
    [https://m66.net/contact] => 
)

When rendering a template, you can decide whether to add an active class to the navigation item based on this boolean value.

Summarize

array_fill_keys is a concise and efficient function that is suitable for quickly generating initial state arrays. It is very convenient to deal with Boolean flags, permission control, navigation status and other scenarios.

Next time you need to initialize a boolean array, you might as well try this method to make your code more concise and readable!