Bobby Bruce
Bobby Bruce

Reputation: 361

Is there a way to set a value for each element in an array?

I'm likely thinking of this wrong, but is there a function to set a static value for each key in a PHP array?

For example, is there a fancy alternative to this:

$staticVal = 1;
$myArray = array('key1'=> $staticVal, 'key2' => $staticVal, 'key3' => $staticVal, 'key4' => $staticVal);

Thanks in advance guys.

Upvotes: 1

Views: 91

Answers (3)

Quique
Quique

Reputation: 47

There are 3 functions which you can use: (not only with a static value)

  • array_map
  • array_filter
  • array_walk

Example about usage of array_map

<?php
$some_other_value = 'any value';
$tmp_arr = range(1, 5);
array_map(function($value) {
    return $some_other_value;
}, $tmp_arr);

// result
/*
[
    1 => 'any value',
    2 => 'any value',
    3 => 'any value',
    4 => 'any value',
    5 => 'any value'
]
*/

Upvotes: 0

Qirel
Qirel

Reputation: 26490

You can combine array_map() and range() to define your keys, and set them as the keys in your array through array_combine().

array_combine() combines two arrays, where one becomes the value, and the other becomes the indexes, in the resulting array. array_map() will create the new indexes, by adding the prefix key in front of each index, created by range(). range() creates an array of values, starting from 1, and all the way up to the number of elements in $myArray. That creates the number of each index, so you'll get key1, key2 and so on, which becomes the keys in the array through array_combine().

This disregards any previous values of the keys, and is independent on the number of elements in the original array.

$staticVal = 1;
$myArray = array($staticVal, $staticVal, $staticVal, $staticVal);

$myArray = array_combine(array_map(function ($k) { 
                             return 'key'.$k; 
                         }, range(1, count($myArray))), 
                         $myArray);
print_r($myArray);

Output:

Array (
    [key1] => 1
    [key2] => 1
    [key3] => 1
    [key4] => 1
)

Upvotes: 2

A l w a y s S u n n y
A l w a y s S u n n y

Reputation: 38552

You can try like this using array_fill_keys()

$staticVal = 1;
$keys = array('key1','key2','key3','key4');
$myArray = array_fill_keys($keys, $staticVal);
print '<pre>';
print_r($myArray);
print '</pre>';

Upvotes: 3

Related Questions