PHP 5.5 implemented the foreach functionality with list. What are the benefits of this?

3

In PHP 5.5, we have a new feature, which is to use list together with foreach .

$array = [
    [1, 2],
    [3, 4],
];

foreach ($array as list($a, $b)) {
    echo "A: $a; B: $b\n";
}

Output is:

A: 1; B: 2
A: 3; B: 4

I understand very well what happens in the call of this foreach , but I would like to know how this can bring benefits in the "real life programming", since the examples in the PHP Manual are always too simple. / p>

What are the benefits of having a foreach with list ? I would like some examples to set the idea.

    
asked by anonymous 13.05.2016 / 14:56

2 answers

2

The advantage is that there is no need to create index variables and retrieve each element of the array using these variables. Everything is provided to you in a simple and compact way. Basically the code gets simpler. Note also that the task of using indexes to access the array is repetitive and does not aggregate anything because the same thing is always done for loops. Therefore, a construct (foreach) that removes this routine task without utility becomes interesting.

It is true that this does not change the way you program, but you will notice that writing loop code without the need to create indexes and instantiate them is quite nice since this task is repetitive and does not add anything to the code , as stated earlier.

My suggestion is: use this construct a few times and then form an opinion. I guarantee you'll like it :).

    
18.05.2016 / 01:48
1

I think the idea is for something more "strange" like:

foreach ($array as list($a, $b, list($c, $d))) {
    echo "A: $a; B: $b; C: $c; D: $d;<br>";
};

Sometimes a foreach can do the whole job ...

But as for your question .. I think it's more of a find than what other languages allow .. In practical terms I think I will never use it, and so suddenly I do not even see a practical utility ..

    
17.05.2016 / 17:10