array_fill_keys(): Fill array with values and keys

$new_array = array_fill_keys ($keys_array, $value);
$keys_array : An array whoes values will be used as keys.

$value: This will be used as filling ( the value of the output array )

Output will be a new array with filled keys and value.

Example with two arrays

$keys=array('One' ,'Two','Three','Four');
$input='First';

$result=array_fill_keys($keys,$input);
while (list ($key, $val) = each ($result)) {
echo "$key -> $val <br>";
}
Output is here.
One -> First 
Two -> First 
Three -> First 
Four -> First 

Example 2

$keys=array('One' ,2,'3','F');
$input='First';

$result=array_fill_keys($keys,$input);
while (list ($key, $val) = each ($result)) {
echo "$key -> $val <br>";
}
Output
One -> First 
2 -> First 
3 -> First 
F -> First

Example 3 : Using associative array

$keys=array('One' ,'Two','Three');
$input=array('First','Second');
$result=array_fill_keys($keys,$input);
print_r($result);
Output
Array ( 
  [One] => Array ( [0] => First [1] => Second )
  [Two] => Array ( [0] => First [1] => Second )
  [Three] => Array ( [0] => First [1] => Second )
  )

Example 4: Initializing a Configuration Array

$config_keys = ['timezone', 'language', 'currency'];
$default_values = array_fill_keys($config_keys, 'default_value');
print_r($default_values);
// Output: Array ( [timezone] => default_value [language] => default_value [currency] => default_value )

Example 5: Placeholder Array with Empty Values

$keys = ['name', 'email', 'phone'];
$placeholders = array_fill_keys($keys, '');
print_r($placeholders);
// Output: Array ( [name] => [email] => [phone] => )

Example 6: Generating a Grid with Default Values

$grid_keys = range(1, 100);
$grid = array_fill_keys($grid_keys, 0);
print_r($grid);
// Output: Array ( [1] => 0 [2] => 0 ... [100] => 0 )

Returns the First Key Creating array
Array REFERENCE
Subhendu Mohapatra — author at plus2net
Subhendu Mohapatra

Author

🎥 Join me live on YouTube

Passionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.



Subscribe to our YouTube Channel here



plus2net.com











PHP video Tutorials
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2025   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer