Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

249
Visualizações
While destructuring an array, can the same element value be accessed more than once?

Since PHP7.1, a foreach() expression can implement array destructuring as a way of unpacking row values and make individualized variable assignments.

When using array destructuring within a foreach() loop, can a specific value be accessed by its associative key more than once?

For example:

$array = [
    ['group' => 'A', 'name' => 'Ann', 'age' => 19],
    ['group' => 'B', 'name' => 'Bea', 'age' => 26],
    ['group' => 'A', 'name' => 'Cam', 'age' => 32],
    ['group' => 'B', 'name' => 'Des', 'age' => 24]
];

I know I can use:

foreach ($array as ['group' => $group, 'name' => $name, 'age' => $age]) {
    // do stuff with $group, $name, and $age
}

But what if I want to access, say, $group a second time while destructuring? Is it possible?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

It seems pretty unorthodox and there will be very few scenarios where it will be useful, but it is possible/valid.

Just repeat the "key => value" syntax again and supply a different variable at the value position. In this context, the keys can be repeated.

Here's a demo of using array destructuring to "spin" a result set with a disembodied foreach loop.

Code: ( Demo )

 $array = [ ['group' => 'A', 'name' => 'Ann', 'age' => 19], ['group' => 'B', 'name' => 'Bea', 'age' => 26], ['group' => 'A', 'name' => 'Cam', 'age' => 32], ['group' => 'B', 'name' => 'Des', 'age' => 24] ]; $result = []; foreach ($array as ['group' => $group, 'group' => $result[$group]['group'], 'name' => $name, 'age' => $result[$group][$name]]); # 1st assignment of group value^^^^^^ # 2nd assignment of group value-------------------^^^^^^^^^^^^^^^^^^^^^^^^ var_export($result);

Production:

 array ( 'A' => array ( 'group' => 'A', 'Ann' => 19, 'Cam' => 32, ), 'B' => array ( 'group' => 'B', 'Bea' => 26, 'Des' => 24, ), )

The same technique also works outside the context of a foreach() loop. ( demo )

 ['one' => $result[], 'one' => $result[]] = ['one' => 1]; var_export($result);

Production:

 array ( 0 => 1, 1 => 1, )
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda