php - create array in while loop - can't figure it out

Joined
12 Feb 2006
Posts
17,313
Location
Surrey
why isn't the below working? the array is being created and returned, however it's just the latest while loop that gets returned. i've tried $timeoff .= array.... but that messes it up. how would i add to the array without resetting it?

PHP:
$timeoff = array();

   while($row = mysqli_fetch_array($result_stafftimes_timeoff)) {
   
$offId =$row['offId'];
$location =$row['location'];
$startdate =$row['startdate'];   
$enddate =$row['enddate'];   
$reason =$row['reason'];   

$timeoff = array
  (
  array($startdate,$enddate,$reason, $location),

  );
  


}

  return($timeoff);
}
 
Soldato
Joined
3 Jun 2005
Posts
3,117
Location
The South
Alternatively you should be able to do -
Code:
$timeoff[] = array($startdate, $enddate, $reason, $location);

Edit - I should have added a bit more info but essentially the code you have creates a new empty array using the $timeoff variable then during your while loop you assign the variable with a new multidimensional array (array( array() ); rather than to an index, which is why you're only seeing the last results.
Using square brackets after an arrays variable denotes that you want to assign a value to a new index, eg - $array_variable[] = 'Bob'.

Where array_push() is useful is when you need to add data to multiple indexes at once, otherwise i'd just stick to the above for simplicity.

I would however recommend reading the PHP 'sites documentation as there's loads of examples - http://php.net/manual/en/language.types.array.php#language.types.array.syntax.modifying.
 
Last edited:
Back
Top Bottom