php

PHP array_fills_keys() Function

array_fill_keys() function in PHP is used to set the value to all the elements present in the given array.

Syntax:
array_fill_keys(array_input,value)

Parameters:

  1. array_input contains the actual array
  2. The second parameter is used to set a value to all the elements in the array_input.

Example 1:

In this example, we will set value-’lotus’ to the array that has 4 elements.

<?php

//create an array named Flower
$Flower1=array('flower_name','sepal','petal','area');
 
print_r("Actual array:");
print_r($Flower1);

//set the value - "lotus" to Flower array
$finalized=array_fill_keys($Flower1,"lotus");

print_r("Final array:");
print_r($finalized);
?>

Output:

We can see that the actual elements in the array are ‘flower_name’,’sepal’,’petal’,’area’. So we will set the value to “lotus” using array_fill_keys().

Example 2:

In this example, we will set the value to 45 for the array that has 4 elements.

<?php

//create an array named Flower
$Flower1=array(100,120,140,566);
 
print_r("Actual array:");
print_r($Flower1);

//set the value - 45 to Flower array
$finalized=array_fill_keys($Flower1,45);

print_r("Final array:");
print_r($finalized);
?>

Output:

We can see that the actual elements in the array are 100, 120, 140, and 566. So we will set the value to 45 using array_fill_keys().

Example 3:

In this example, we will set value-45 to the array that has no elements.

<?php

//create an array named Flower
$Flower1=array();
 
print_r("Actual array:");
print_r($Flower1);

//set the value - 45 to empty array
$finalized=array_fill_keys($Flower1,45);

print_r("Final array:");
print_r($finalized);
?>

Output:

We can see that there are no elements in the actual array. Now, we will set the value to 45 using array_fill_keys(). We can see that no error is returned and 45 is not added as a value to the empty array.

Conclusion

The array_fill_keys() function adds values to the array. It sets only one value for the entire array. If there are no elements in the actual array and we are trying to add a value to the empty array, it will not add and return the empty array without returning an error.

About the author

Gottumukkala Sravan Kumar

B tech-hon's in Information Technology; Known programming languages - Python, R , PHP MySQL; Published 500+ articles on computer science domain