Welcome to this comprehensive guide on using the array_fill() function in PHP! In this tutorial, we'll explore how to use this function to fill arrays with a specific value. Let's dive right in! π―
array_fill() is a PHP function used to fill an array with a specific value. This function comes in handy when you want to create an array with the same value repeated multiple times. π‘
To use array_fill(), you first need to understand the syntax:
array_fill(start, number_of_elements, value)start: The index from which filling should start.number_of_elements: The number of elements to be filled.value: The value to be filled in the specified elements.Here's a simple example:
<?php
$myArray = array_fill(0, 5, "Hello");
print_r($myArray);
?>
Output:
Array
(
[0] => Hello
[1] => Hello
[2] => Hello
[3] => Hello
[4] => Hello
)In this example, we created an array called $myArray and filled it with the string "Hello" starting from index 0 and continuing for 5 elements. β
You can also fill an array with different values for each group of elements using the array_fill_keys() function. Here's an example:
<?php
$keys = array(0, 2, 4);
$values = array("One", "Two", "Three");
$myArray = array_fill_keys($keys, $values);
print_r($myArray);
?>
Output:
Array
(
[0] => One
[2] => Two
[4] => Three
)In this example, we created an array called $myArray and filled it with the values from the $values array using the keys from the $keys array. π
What does the `array_fill()` function do in PHP?
We hope this tutorial has helped you understand the PHP array_fill() function better. Stay tuned for more tutorials on PHP, and happy coding! π