PHP array_fill Function: Fill Array with Same Value

PHP array_fill

You can use the array_fill function in PHP when you must fill an array with one value. You may want to set default values in a form or to prepare a list with repeated values for quick use.

Understand the array_fill Function in PHP

The array_fill function creates an array and fills it with one value. You set the start index, the number of elements, and the value.

Here is the syntax:

array_fill($start_index, $count, $value)
  • $start_index – The index for the first element in the array.
  • $count – The number of elements in the array.
  • $value – The value that will fill each element.

PHP makes a loop inside its code when you run the function. The loop starts at the given index and runs until it creates the required number of elements. Each element gets the same value.

You can use this function to prepare arrays with default options. It can also help in tests where you need repeated data. You may also use it when you must fill large arrays quickly.

Here is a quick example:

$array = array_fill(0, 4, 'apple');
print_r($array);

This code creates an array with four items. Each item holds the word “apple”. The index starts from zero and ends at three.

Here is the output:

Array
(
[0] => apple
[1] => apple
[2] => apple
[3] => apple
)

Use the array_fill with Arrays

Create indexed arrays with array_fill:

$list = array_fill(0, 5, 10);
print_r($list);

This will produce indexes from zero to four with the value ten. The output:

Array
(
[0] => 10
[1] => 10
[2] => 10
[3] => 10
[4] => 10
)

Use array_fill with numeric indexes:

$data = array_fill(5, 3, 'yes');
print_r($data );

This creates keys five to seven with the value “yes”. The output:

Array
(
[5] => yes
[6] => yes
[7] => yes
)

Combine array_fill with array_map for Dynamic Values:

$base = array_fill(0, 5, 0);
$result = array_map(function($v, $i) { return $i * 2; }, $base, array_keys($base));
print_r($result);

This creates values that depend on the index. The output:

Array
(
[0] => 0
[1] => 2
[2] => 4
[3] => 6
[4] => 8
)

So, how does array_fill handle negative indexes?

If you use a negative start index, PHP still creates the array. The index begins at the negative number and grows from there.

For example:

$array = array_fill(-2, 3, 'test');

This creates keys -2, -1, and 0. Here is the output:

Array
(
[-2] => test
[-1] => test
[0] => test
)

Examples of array_fill in PHP

Fill a List with the Same Number:

$numbers = array_fill(0, 5, 100);
print_r($numbers);

This creates five items with the number one hundred. The count begins at index zero. You can use it to prepare lists with fixed values before you add more data.

Start from a Non-zero Index:

$data = array_fill(3, 4, 'ready');
print_r($data);

This fills keys three to six with the word “ready”. It can help when you must keep lower indexes for other data.

Use Negative Index:

$items = array_fill(-3, 3, 'on');
print_r($items);

This starts from index -3 and ends at -1. It is useful when you need to match certain key rules in a program.

Wrapping Up

In this article, you learned the array_fill function and its uses in PHP. You also saw how it works with different types of indexes and how it pairs with other functions.

Here is a quick recap:

  • array_fill creates arrays with repeated values.
  • You can set the start index to zero, a positive number, or a negative number.
  • It works with other functions to produce dynamic results.
  • It works the same in PHP 7 and 8, but error handling differs

FAQs

How to use array_fill in PHP to create a simple array?

$result = array_fill(0, 5, "apple");  
print_r($result);
This code creates an array with 5 elements. Each element has the value apple. Indexes start from 0.

What is the difference between array_fill and array_fill_keys in PHP?

array_fill sets values based on numeric indexes.
$arr1 = array_fill(0, 3, "x");  
print_r($arr1);
array_fill_keys sets values for given keys.
$arr2 = array_fill_keys(["a", "b", "c"], "x");  
print_r($arr2);

Can array_fill in PHP use negative start indexes?

Yes, negative indexes are possible.
$arr = array_fill(-2, 3, "pear");  
print_r($arr);
Indexes will start at -2, then -1, then 0.

How to fill an array with default values using array_fill in PHP?

$defaults = array_fill(0, 4, "N/A");  
print_r($defaults);
This creates 4 elements with the value N/A. Useful for placeholders.

Similar Reads

PHP array_merge: Combine Multiple Arrays into One

You have two or more arrays. You want one. That is the problem array_merge solves in PHP. This function lets…

PHP function_exists: Avoid Function Redeclaration

The function_exists() function in PHP checks whether a given function is defined or not. The function_exists() function works for both…

PHP Callable & Callback: Pass a Function to Another

The callback in PHP lets you pass functions as arguments and reuse code. It helps you to control how tasks…

Traits in PHP: What They Are & Examples

PHP introduced traits to solve a problem with code reuse. Before traits, developers used inheritance and interfaces to share functionality…

PHP is_dir Function: Check if a Directory Exists

Sometimes, when you run a script, you may encounter an error because the directory you're trying to access doesn't exist.…

PHP Elvis Operator: How (?:) Works with Examples

The Elvis operator in PHP is a shorthand version of the ternary operator. PHP allows developers to use this conditional…

PHP break Statement: How to Exit a Loop

The PHP break statement helps in controlling the flow of loop work. It gives you a way to stop a…

PHP Anonymous Function: How It Works with Examples

The anonymous function in PHP lets you define a small task that doesn’t require a function name. Understand the Anonymous…

PHP array_filter: How to Filter Array Values with Examples

You can use array_filter in PHP to remove unwanted data from arrays. It works with a custom callback or default…

PHP filter_input: How to Validate Input Securely

User input can be risky. Hackers exploit weak validation to inject malicious data. PHP filter_input() helps you sanitize and validate…

Previous Article

Object to Primitive Conversion in JavaScript with Examples

Next Article

HTML samp Tag: How to Show Sample Program Output

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *


Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.