Syntactic Sugar in PHP

3

Would foreach be an implementation of Syntactic Sugar in PHP?

foreach($array as $key=>$values) {
    //Faz algo com as chaves e valores.
}
    
asked by anonymous 25.07.2014 / 21:33

3 answers

4

Yes, since you would not need it to achieve such a result, as well as many other functions: while and do while .

But, the languages must evolve and this ends up being considered natural with time (after all nobody wants to be writing reps for with if and GOTO ).

    
25.07.2014 / 21:44
3

Virtually all repetition structures ( for , foreach , do-while , for-in ) of the most modern programming languages can be considered syntactic sugar for the simplest structure of all, while which has been present in PHP since version 4). So the answer is yes.

It is worth remembering that syntactic sugar are language structures that allow you to perform a task in a "simpler" way than by the more "low level" form. For example, if we compare for and while in PHP:

While:

$i = 0;
while ($i <= 10):
    echo $i;
    $i++;
endwhile;

for:

for ($i = 0; $i <= 10; $i++) {
    echo $i;
}

Most people find the second form simpler and readable. However, in terms of computing, both forms are equivalent.

    
25.07.2014 / 21:46
2

According to the manual , yes and no.

For example, they are identical:

<?php
$arr = array("one", "two", "three");
reset($arr);
while (list(, $value) = each($arr)) {
    echo "Value: $value<br />\n";
}

foreach ($arr as $value) {
    echo "Value: $value<br />\n";
}
?>

and

<?php
$arr = array("one", "two", "three");
reset($arr);
while (list($key, $value) = each($arr)) {
    echo "Key: $key; Value: $value<br />\n";
}

foreach ($arr as $key => $value) {
    echo "Key: $key; Value: $value<br />\n";
}
?>

However, this is no longer the case:

<?php 
$arr = array(1,2,3,4,5,6,7,8,9); 

foreach($arr as $key=>$value) 
{ 
    unset($arr[$key + 1]); 
    echo $value . PHP_EOL; 
} 
?> 

Output: 1 2 3 4 5 6 7 8 9

and in this:

<?php 
$arr = array(1,2,3,4,5,6,7,8,9); 

while (list($key, $value) = each($arr)) 
{ 
    unset($arr[$key + 1]); 
    echo $value . PHP_EOL; 
} 
?> 

Output: 1 3 5 7 9

    
25.07.2014 / 21:48