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
3
  • 3
    You don't need the inner loop. Right now, you're filling up an array with ten identical elements, ten separate times. Commented Apr 22, 2020 at 13:11
  • 2
    You just need the while() loop and $colors[] = $row[0]; Commented Apr 22, 2020 at 13:13
  • @NigelRen Thank you! This did the trick Commented Apr 22, 2020 at 13:16

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Where does $i come from in your last snippet?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.