PHP syntactic sugar code example

According to Wikipedia, Syntactic sugar is syntax within a programming language that is designed to make things easier to read or to express.

Though PHP doesn’t necessarily have much concept of sugaring, I across this one example sometime back. The idea here is to add a given set of values to an array but at the alternating ends.

Example

For a given set of values, 10, 12, 124, 349, 43, 0, 493, 3, 32. The output should have values pushed to each end alternatively. So, the first value into the array would be 10, 2nd would be 12, pushed to the end (or at the start), 3rd pushed other and so on.

#1    #2    #3    #4    #5    #6    #7    #8    #9
                                                32
                                    493   493   493
                        43    43    43    43    43
            124   124   124   124   124   124   124
10    10    10    10    10    10    10    10    10
      12    12    12    12    12    12    12    12
                  349   349   349   349   349   349
                              0     0     0     0
                                          3     3

The function here loops over an array pushes values in array $e alternatively.

$x = [10, 12, 124, 349, 43, 0, 493, 3, 32];
$i = 0;
foreach ($e as $v) {
      (array_.[unshift,push][++$i%2])($e,$d);
}

It’s an array with the two function names ['array_push','array_unshift'] with [++$i%2] as the index of the array alternating between a 0 or 1 so will evaluate to the other function each time. PHP’s “variable functions” let you assign a variable to a function and execute by calling with parenthesis (ex: $f='array_push'; $f($e,$d); == array_push($e,$d)) so the ($e,$d) is then calling the evaluated element of the array.

Just a shorter way to do

if (++$i%2)
      array_push($e,$d);
else
      array_unshift($e,$e);
Follow me
Latest posts by Abhishek Gupta (see all)

Leave a Reply