Ver Mensaje Individual
  #2 (permalink)  
Antiguo 19/05/2007, 03:05
clinisbut
 
Fecha de Ingreso: diciembre-2004
Mensajes: 278
Antigüedad: 19 años, 4 meses
Puntos: 0
Re: Foreach repite penultima posicion

Siempre me pasa igual, pregunto aquí e inmediatamente encuentro la solución.
Encontrado en php.net:
Cita:
With foreach and references, there is a super easy way to corrupt your data

see this test script:
<?php
$array = array(1,2,3);
foreach( $array as &$item );
foreach( $array as $item );
print_r( $array );
?>

You would imagine that it would have 1,2,3 but in reality, it outputs 1,2,2

The issue is that $item is a pointer to the last array value, and exists outside of the scope of the foreach, so the second foreach overwrites the value. If you would check what it gets set to in the second foreach loop, you would see that it gets set to 1 and then 2 and then 2 again.

This has already been filed as a bug, see:
http://bugs.php.net/bug.php?id=29992

but php developers seem to think that it's expected behaviour and *good* behaviour, so it's doubtful that it will change anytime soon. This is a really bad gotcha, so watch out.
Y en respuesta a él:
Cita:
php at kormoc dot com 11-May-2006 10:25 wrote:
With foreach and references, there is a super easy way to corrupt your data.

But you can avoid it by destruction of the hard link $item

<?php
$array = array(1,2,3);
foreach( $array as &$item );
unset($item);
foreach( $array as $item );
print_r( $array );
?>
En definitiva, que si uso el mismo nombre de $variable (en mi caso $p) en dos foreach's diferentes (de los cuales el primero no copia el valor si no que lo referencia con &), antes del segundo bucle debo vaciar la $variable con unset() (por ejemplo), quedándome así el código:
Código PHP:
foreach( $parametros as &$p )
{
 ....
blablabla
}
unset(
$p);
foreach( 
$parametros as $p ){
{
  ....
blablabla

Un saludo y gracias igualmente a quien haya entrado