There is no dictionary comprehension syntax in PHP. When looking for the shortest and/or most efficient code to produce the same output, I would propose this:
1. range(from, to, step)
You can make use of the third parameter of the range function:
$d = array_combine (range(0,8,2), range(0,12,3));
Output of var_export($d)
:
array (
0 => 0,
2 => 3,
4 => 6,
6 => 9,
8 => 12,
)
Of course, this only works if your expressions are linear.
2. foreach
The foreach
loop really is the cleanest and most readable way to handle this. Note that you have a little error in your version: the range function needs at least 2 arguments.
Also, PHP does not require you to initialise $d as it will do so upon the first assignment in the loop. Finally, you don't need the braces, although your preferred coding style may require the use of them:
foreach (range(0,4) as $x) $d[$x*2] = $x*3;
In number of characters this line is even shorter than the first solution.