note 56234 modified in language.types.array by nforbes

From: Date: Fri, 18 Aug 2006 21:56:52 +0000
Subject: note 56234 modified in language.types.array by nforbes
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-116060@lists.php.net to get a copy of this message
[Editor's note: You can achieve what you're looking for by referencing $single, rather than copying it by value in your foreach statement. See http://php.net/foreach for more details.] Don't know if this is known or not, but it did eat some of my time and maybe it won't eat your time now... I tried to add something to a multidimensional array, but that didn't work at first, look at the code below to see what I mean: <?php $a1 = array( "a" => 0, "b" => 1 ); $a2 = array( "aa" => 00, "bb" => 11 ); $together = array( $a1, $a2 ); foreach( $together as $single ) { $single[ "c" ] = 3 ; } print_r( $together ); /* nothing changed result is: Array ( [0] => Array ( [a] => 0 [b] => 1 ) [1] => Array ( [aa] => 0 [bb] => 11 ) ) */ foreach( $together as $key => $value ) { $together[$key]["c"] = 3 ; } print_r( $together ); /* now it works, this prints Array ( [0] => Array ( [a] => 0 [b] => 1 [c] => 3 ) [1] => Array ( [aa] => 0 [bb] => 11 [c] => 3 ) ) */ ?> --was-- Don't know if this is known or not, but it did eat some of my time and maybe it won't eat your time now... I tried to add something to a multidimensional array, but that didn't work at first, look at the code below to see what I mean: <?php $a1 = array( "a" => 0, "b" => 1 ); $a2 = array( "aa" => 00, "bb" => 11 ); $together = array( $a1, $a2 ); foreach( $together as $single ) { $single[ "c" ] = 3 ; } print_r( $together ); /* nothing changed result is: Array ( [0] => Array ( [a] => 0 [b] => 1 ) [1] => Array ( [aa] => 0 [bb] => 11 ) ) */ foreach( $together as $key => $value ) { $together[$key]["c"] = 3 ; } print_r( $together ); /* now it works, this prints Array ( [0] => Array ( [a] => 0 [b] => 1 [c] => 3 ) [1] => Array ( [aa] => 0 [bb] => 11 [c] => 3 ) ) */ ?> http://php.net/manual/en/language.types.array.php

« previous php.notes (#116060) next »