Reputation: 4267
I am reading through a python piece of code that I need to understand in order to port it in PHP. I can understand basic python syntax. However I came across following piece of code, and I do not really get it.
player = next((p for p in player_list if p['team'] == team), None)
As in, is it doing the following:
if p['team'] == team
for p in player_list
next
is doing here :(I just need to understand the syntax/grammar of above statement, so I can write equivalent in PHP. I unable to figure it out since PHP does not support such constructs. Any help is appreciated
Upvotes: 1
Views: 49
Reputation: 522135
That is a generator expression with a conditional. p for p in player_list
iterates through all values in player_list
and yields them, but only if p['team'] == team
. next
advances the iterator and gets its next value. Usually that would end in a StopIteration
exception if the iterator reaches its end [without finding a value], which the second None
parameter prevents; next
will return None
instead of raising the exception.
In short: this snippet finds the first player in player_list
who is of team team
, if there's none then None
is assigned to player
. In PHP the closest equivalent is something like:
$player = array_reduce($playerList, function ($a, $p) use ($team) {
return $a ?: $p['team'] == $team ? $p : null;
});
or:
$player = array_filter($playerList, function ($p) use ($team) {
return $p['team'] == $team;
})[0] ?? null;
Though note neither is short-circuiting like next
is but both variations iterate the entire array. Therefore you'd probably use a foreach
loop with an if
and a break
instead.
Upvotes: 2