Today I Learned - Rocky Kev

TIL an easy way to populate an data array

POSTED ON:

TAGS:

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)

Php.net manual


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

Php.net manual


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

TIL how NGINX knows to look for index.html vs index.php

What happens when visitor hits /foo/bar URL?

TIL php-fpm

PHP runs as a separated service when using PHP-FPM. By using this PHP version as language interpreter, requests are processed through a TCP/IP socket; so that the Nginx web server only handles the HTTP requests and PHP-FPM interprets the PHP code. The fact of having two separate services is key for increasing efficiency.

TIL the difference between single-threaded & multi-threaded architecture

For web dev, we don't need it. We're not bottle-necked by the processing power. We're instead bottlenecked by the ability to read files/databases. We can simulate multi-threading (and improve our app's performance) using async/await.