PHP Array array_fill() Function (With Examples)

In this tutorial, we will learn about the PHP array_fill() function with its usage, syntax, parameters, return value, and examples. By IncludeHelp Last updated : December 31, 2023

PHP array_fill() Function

The array_fill() function is used to fill the n elements in an array from given index with the specific value.

Syntax

The syntax of the array_fill() function:

array_fill(index, n, value) : array

Parameters

The parameters of the array_fill() function:

  • index is the starting position from where we have to start filling the elements.
  • n is the total number of elements to be filled from given “index”.
  • value is any string, integer etc value to be filled.

Return Value

The return type of this method is array, it returns the filled array.

Sample Input/Output

Input:
index = 3
n = 5
value = "Okay"

Output:
Array
(
    [3] => Okay
    [4] => Okay
    [5] => Okay
    [6] => Okay
    [7] => Okay
)

PHP array_fill() Function Example

<?php
//filling from 3rd index 
$arr1 = array_fill(3, 5, "Okay");	
print_r ($arr1); 

//filling from 0th index to next 5
//i.e. from index 0 to 4
$arr2 = array_fill(0, 5, "Hello");
print_r ($arr2); 
?>

Output

The output of the above example is:

Array
(
    [3] => Okay
    [4] => Okay
    [5] => Okay
    [6] => Okay
    [7] => Okay
)
Array
(
    [0] => Hello
    [1] => Hello
    [2] => Hello
    [3] => Hello
    [4] => Hello
)

To understand the above example, you should have the basic knowledge of the following PHP topics:

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.