1

I have a table called statussen in my database with 10 colors. Now I want to put those colors in an array so I can make use of them, I placed 2 markers in my code because at Marker1 the array is filled completely normal with the 10 colors. But as soon as I get out of the while loop (where Marker2 is), the only color that is left is the very last one. I also found this question on here : array is overwritten by the last element in php. But I don't think it applies to my problem. Thanks ahead for all the help

$colors = array();
$result = mysqli_query($_SESSION['conn'], "SELECT kleur FROM statussen;");
while ($row=mysqli_fetch_row($result)) 
{
    for ($i = 0;$i < 10; $i++)
    {
        $colors[$i] = $row[$i];
    }
    //Marker1
}
//Marker2
Arno Gouwy
  • 33
  • 4

1 Answers1

1

As of my understanding :

You are using while loop which loop through array one by so there is only one record inside while loop at a time and so does for for loop(which is not required)

The second thing is you are adding index $colors[$i]. Every time for loop get initialised it set $i = 0 and this means that it set value to $colors[0] = $row[$i] so that it gets override.

You can directly use code like this:

$colors = array();
$result = mysqli_query($_SESSION['conn'], "SELECT kleur FROM statussen;");
while ($row=mysqli_fetch_row($result)) 
{
    $colors[] = $row[$i];
}
//Marker2

notice that there is no index provide to colors array $colors[], in this case PHP automatically add increment index to it starting from 0.

Paritosh Mahale
  • 1,238
  • 2
  • 14
  • 42