Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

494
Vistas
Within a foreach() expression, is the value defined before or after the key?

In a classic foreach() loop after the word as, is it possible to use the key variable as part of the value variable or vice versa?

* after more than a decade of PHP development, this possibility only just now occurred to me to investigate.

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

A foreach() always assigns the value variable before assigning the key variable. (Demo)

This seems a little counterintuitive because $v visually appears to be declared after it is access by key declaration.

This means you can safely use:

$array = ['a', 'b'];
$result = [];
foreach ($array as $result["prefix_$v"] => $v);
var_export($result);

to produce:

array (
  'prefix_a' => 0,
  'prefix_b' => 1,
)

The newly generated array has prefixed keys based on the original values and the original indexes become the new values.

Without the prefix_ prepended to the string, the action is effectively the same as array_flip().


Reversing the assignments so that the value variable receives the key does not work as intended. You might hope to generate ["prefix_0", "prefix_1"] but it does not and it also generates Notices/Warnings due to trying to access an undeclared variable. (The complaint is only on the first iteration because after the first iteration, $k is declared -- it is the previous iteration's key.)

$array = ['a', 'b'];
$result = [];
foreach ($array as $k => $result["prefix_$k"]);
// not defined on first iteration -------^^
var_export($result);

Bad Output:

Warning: Undefined variable $k in /in/iVm1u on line 6
array (
  'prefix_' => 'a',
  'prefix_0' => 'b',
)

For additional context, I'll offer one more working example that generates a multi-dimensional array using the value to determine the array keys in the output array. (Demo)

$array = [2, 3, 5];

$result = [];
foreach ($array as $result[$v * $v][$v] => $v);
var_export($result);

Output:

array (
  4 => 
  array (
    2 => 0,
  ),
  9 => 
  array (
    3 => 1,
  ),
  25 => 
  array (
    5 => 2,
  ),
)
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda