Wvs
Wvs

Reputation: 45

Set array in while use outside while

I created a script where I set a array in an existing array through a while loop from a SQL database.

while ($nextday = odbc_fetch_array($nextdayinfo)){
$username = $nextday['user_sign'];
  if(isset($username)){
  $nextday[] = array('value' => $username, 'text' => $username);
  }
}

This is the code. If I try to print_r($nextday) after the IF clause, it will show me all the information, as soon as i put the print_r($nextday) after the while clause, it stops working.

Upvotes: 1

Views: 106

Answers (1)

Jerodev
Jerodev

Reputation: 33186

You are using the same variable for the fetched database row as your array. So the array is overwritten by the new row at every iteration.

Try defining your array outside of the loop and using a different name.

$array = [];
while ($nextday = odbc_fetch_array($nextdayinfo)) {
    $username = $nextday['user_sign'];
    if (isset($username)) {
        $array[] = [
            'value' => $username, 
            'text' => $username
        ];
    }
}

print_r($array);

Upvotes: 2

Related Questions