I’m using PHP. I would like to add same value to several array keys.
This works:
JavaScript
x
$array = array();
$value = 1000;
$from = 1;
$to = 5;
for ($i = $from; $i <= $to; $i++)
{
$array[$i] = $value;
}
$value = 2000;
$from = 10;
$to = 14;
for ($i = $from; $i <= $to; $i++)
{
$array[$i] = $value;
}
print "<pre>";
print_r($array);
print "</pre>";
Anyway, I’m looking for a shorter way. So, I have tried this:
JavaScript
$array = array();
$array[range(1, 5)] = 1000;
$array[range(10, 14)] = 2000;
print "<pre>";
print_r($array);
print "</pre>";
This did not work at all.
Any ideas how the job could be done with less code?
Advertisement
Answer
the obvious and most readable variant is:
JavaScript
$array = array();
for ($i=1; $i<=5;$i++) $array[$i] = 1000;
for ($i=10; $i<=14;$i++) $array[$i] = 2000;
another option is:
JavaScript
$array = array();
$array = array_fill_keys(range(1,5), 1000) + $array;
$array = array_fill_keys(range(10,14), 2000) + $array;