TIL an easy way to populate an data array
POSTED ON:
TAGS: php javascript
Bonus - I just had to do this in PHP as well, so you get TWO languages for the price of one TIL!
(And I pass the savings on to you!)
Javascript #
Using Fill -- arrays:
let filledArray = new Array(10).fill('hello');
// RESULT:
// ["hello","hello","hello","hello","hello","hello","hello","hello","hello","hello"]
Using Fill -- array with objects:
// referencing the same object
let filledArrayObject = new Array(10).fill({'hello':'goodbye'});
// referencing unique objects
let filledArrayObjectUnique = new Array(10).fill(null).map(()=> ({'hello':'goodbye'}))
// RESULT:
// [
// { hello: "goodbye"},
// { hello: "goodbye"},
// ...
// { hello: "goodbye"}
// ]
PHP #
Using array_fill
array_fill(int $start_index, int $count, mixed $value)
$a = array_fill(0, 10, 'hello');
// RESULT:
// Array
// (
// [0] => hello
// [1] => hello
// [2] => hello
// [3] => hello
// [4] => hello
// [5] => hello
// [6] => hello
// [7] => hello
// [8] => hello
// [9] => hello
// )
Using array_fill_keys
array_fill_keys(array $keys, mixed $value): array)
$i = 0;
$array = [];
while ($i < 10) {
$array[] = "hello" . $i;
$i++;
}
print_r(array_fill_keys($array, 'goodbye'));
// RESULT:
// Array
// (
// [hello0] => goodbye
// [hello1] => goodbye
// [hello2] => goodbye
// [hello3] => goodbye
// [hello4] => goodbye
// [hello5] => goodbye
// [hello6] => goodbye
// [hello7] => goodbye
// [hello8] => goodbye
// [hello9] => goodbye
// )
Related TILs
Tagged: php