tmyonline Posted February 18, 2008 Share Posted February 18, 2008 Hi guys: I have a 2D associative array in a foreach loop like this: foreach (boolean expression) { $myArray = array ( "element_1" => array("x1", "y1", "z1") ); } Everytime through the loop, I want to add the "element_i" associated with values (xi, yi, and zi) to the $myArray. At the moment, what happens is that the $myArray does not expand because the element_1 and (x1, y1, and z1) are being overwritten by the new values. Consequently, when the loop finishes, the $myArray is the same as it was. I want it to be such that, after 2 iterations, it would add two rows like this: foreach (boolean expression) { $myArray = array ( "element_1" => array("x1", "y1", "z1"), "element_2" => array("x2", "y2", "z2"), "element_3" => array("x3", "y3", "z3") ); } instead of overwriting the element_1 and (x1, y1, z1). What is your recommendation ? Thanks. Link to comment https://forums.phpfreaks.com/topic/91637-how-to-add-a-new-element-to-a-2d-array/ Share on other sites More sharing options...
53329 Posted February 18, 2008 Share Posted February 18, 2008 Personally I'd just add a counter. Not sure if there is an easier way but I know it would work. $counter=0; foreach (boolean expression) { $myArray = array ( "element_" . $counter => array("x1", "y1", "z1"), ); $counter++; } Link to comment https://forums.phpfreaks.com/topic/91637-how-to-add-a-new-element-to-a-2d-array/#findComment-469318 Share on other sites More sharing options...
sasa Posted February 18, 2008 Share Posted February 18, 2008 try <?php for ($x=0;$x<9;$x++) { $i++; $myArray['element_'.$i] = array ("x$i", "y$i", "z$i"); } print_r($myArray); ?> Link to comment https://forums.phpfreaks.com/topic/91637-how-to-add-a-new-element-to-a-2d-array/#findComment-469320 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.