The problem is that I get only the last value comming from the Table. I think its because I am building the array while referencing its values to the same object, and it keeps changing. I know while loop doesnt create a new scope for each iteration which IS the problem.
What’s the best way to get a new scope for each iteration?
Code:
$namesArray= array();
while ($row=mysql_fetch_array($result))
{
$nameAndCode->code = $row['country_code2'];
$nameAndCode->name = $row['country_name'];
array_push($namesArray,$nameAndCode);
}
return $namesArray;
You need to create a new object on each iteration:
Otherwise you’re referencing the same object over and over, and just overwriting its values.
You also can do this with arrays if you don’t require objects:
Or more concisely: