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

Asked

Viewed 78 times

3

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

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

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

Exit is:

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

I understood very well what happens in the flame of this foreach, but I would like to know how this can bring benefits in the "real life of programming", because the examples of the PHP Manual are always too simple.

What are the benefits brought by being able to accomplish a foreach with list? I would like some examples to fix the idea.

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 is simpler. Note also that the task of using indexes to access the array is repetitive and adds nothing because it is always done the same thing for loops. Therefore, a construct (foreach) that removes this useless routine task 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 very nice, since such a task is repetitive and adds nothing to the code, as said before.

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

1

I think the idea is for more "weird" things 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 all the work...

But as for your question.. I think it’s more like finding out what the other languages allow.. In practical terms I think I’ll never use, and so suddenly I don’t even see a practical use..

Browser other questions tagged

You are not signed in. Login or sign up in order to post.