PHP array question

willsherwood
willsherwood used Ask the Experts™
on
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?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Expert of the Year 2014
Top Expert 2014
Commented:
what is the benefit
There isn't any from what you have posted, maybe an inexperienced programmer who didn't understand the results are an array.

Author

Commented:
thanks for the confirmation
Dave BaldwinFixer of Problems
Most Valuable Expert 2014

Commented:
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.
Expert of the Year 2014
Top Expert 2014

Commented:
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)
Dave BaldwinFixer of Problems
Most Valuable Expert 2014

Commented:
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.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial