$new_array = array_fill_keys ($keys_array, $value);
$keys_array : An array whoes values will be used as keys.$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
$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
$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 )
)
$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 )
$keys = ['name', 'email', 'phone'];
$placeholders = array_fill_keys($keys, '');
print_r($placeholders);
// Output: Array ( [name] => [email] => [phone] => )
$grid_keys = range(1, 100);
$grid = array_fill_keys($grid_keys, 0);
print_r($grid);
// Output: Array ( [1] => 0 [2] => 0 ... [100] => 0 )
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.