Skip to content
Advertisement

PHP and adding same value to several array keys

I’m using PHP. I would like to add same value to several array keys.

This works:

$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:

$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:

$array = array();
for ($i=1; $i<=5;$i++) $array[$i] = 1000;
for ($i=10; $i<=14;$i++) $array[$i] = 2000;

another option is:

$array = array();
$array = array_fill_keys(range(1,5), 1000) + $array;
$array = array_fill_keys(range(10,14), 2000) + $array;
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement