Link to home
Start Free TrialLog in
Avatar of willsherwood
willsherwood

asked on

PHP array question

I have an inherited script that has the loop:

      
while($row = mysql_fetch_array($result)) {
		$result_array[] = $row;
	}
         foreach ($result_array as $result) {
        ... }

Open in new window


what is the benefit of splitting this seemingly common/conventional (mysql results) loop into two loops?
and doesn't the first loop just copy the array, row by row?
ASKER CERTIFIED SOLUTION
Avatar of Gary
Gary
Flag of Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of willsherwood
willsherwood

ASKER

thanks for the confirmation
Actually, that isn't true.  That method gets all the data from MySQL at once and puts it into an array of arrays.  It's not just 'copying' it.  Then the 'foreach' is used to go thru the results to do what you want.

The functions of getting the data from the database and generating the display for the page are broken into two separate sections this way.  It also clears all the data from the database query so you can reuse that query.  Until all the data is retrieved, you can't 're-use' that query, you would have to make a new one.

This is even more useful when you have more than one database array to deal with.  I have pages that get three different arrays from the database that are then used for different sections of the page.  The second and third arrays are dependent on content from the first one.
Well if you are sticking with the old mysql library it would be easier to just use fetch_array
But the answer was based on the posted code
(or better still move to PDO)
I've moved everything to 'mysqli'.  It has nothing really to do with the particular library but the method that is being used.  I use it a lot for the reasons I stated.