Search code examples
phparraysappendarrayofarrays

Create array of associative arrays


I want to create an array of associative arrays in a while loop. In each iteration of the while loop I want to add a new element in the array. How I can do that? After that I want to pass this array in a foreach and print the data. I have this part of code for now but obviously something is wrong with that.

while($row2 = mysql_fetch_array($result))
{ 
    $myarray = array("id"=>$theid, "name"=>name($id), "text"=>$row2['text']);
}

Solution

  • To add an element in the end of an array use []
    Example:

    $myarray[] = array("id"=>$theid, "name"=>name($id), "text"=>$row2[text]);