xms
xms

Reputation: 437

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?

Upvotes: 0

Views: 91

Answers (5)

Michael Haddad
Michael Haddad

Reputation: 4435

$a = array_fill(1, 5, 1000);
$b = array_fill(10, 5, 2000);
$array = $a + $b;

If you want $from and $to variables you can use the following code:

$a = array_fill($from_1, $to_1 - $from_1 + 1, 1000);
$b = array_fill($from_2, $to_2 - $from_2 + 1, 2000);
$array = $a + $b;

Upvotes: 2

matt2000
matt2000

Reputation: 1073

The built-in function array_map takes a function to apply to every element in an array. That function can simple return the desired value.

array_map(function () use ($value){return $value;}, array_flip(range(1,5)));

A complete (ugly, unreadable, not recommended) one-line solution could be:

print_r(array_filter(array_map(function ($v){return $v < 5 ? 10000 : ($v > 8 ? 20000 : false);}, array_flip(range(1,14))))); 

Upvotes: 0

Mogzol
Mogzol

Reputation: 1405

There isn't really a better way than by using a for loop (there are some shorter solutions, but they are much less readable and/or perform much worse). If you are doing this a lot why not turn it into a function:

function array_set(&$array, $start, $end, $value) {
    for ($i = $start; $i <= $end; $i++) {
        $array[$i] = $value;
    }
}

Then use it like:

$test = array();

array_set($test, 3, 5, 1000);

var_dump($test);

Which produces: array(3) { [3]=> int(1000) [4]=> int(1000) [5]=> int(1000) }

Upvotes: 1

Iłya Bursov
Iłya Bursov

Reputation: 24146

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;

Upvotes: 0

usrNotFound
usrNotFound

Reputation: 2800

This might help

array_fill_keys(array(1, 2, 3, 4, 5), 10000);
array_fill_keys(array(10, 11, 12, 13, 14), 20000);

Other way would be

array_fill_keys(array_values(range(1,5)), 10000);
array_fill_keys(array_values(range(10,14)), 20000);

Cheers

Upvotes: 1

Related Questions