...

View Full Version : PHP while($var = $arr) question



jaywhy13
08-12-2008, 05:08 PM
I realized today that I can't be too sure of how that construct works...
In php, I'm used to doing this...
while($row = pg_fetch_array($result)){
// do something
}

However... today I did this....
function getRows($result){
return pg_fetch_array($result);
}

and tried

while($row = getRows($result)){
// do something...
}

But that never terminated... Why is that? What do I need to do to get that to work and terminate?

derzok
08-12-2008, 05:14 PM
I *think* the reason it is not terminating is because you are pulling the same item out of the array over and over. When you do while($item = some_fetch_function($sql_result)) you're iterating through the $sql_results. When you abstract it further by making your own function to do that, you're starting your iteration over each time - never moving to the next result.

You might be able to fix this with the use of references.

jaywhy13
08-12-2008, 05:46 PM
I *think* the reason it is not terminating is because you are pulling the same item out of the array over and over. When you do while($item = some_fetch_function($sql_result)) you're iterating through the $sql_results. When you abstract it further by making your own function to do that, you're starting your iteration over each time - never moving to the next result.

You might be able to fix this with the use of references.

Sorry, could you be a bit more specific re the "use of references" part?

CFMaBiSmAd
08-12-2008, 06:15 PM
You can only return variables by reference, not the result of a statement.return statement; does not work. You will need to do the following -


$var = pg_fetch_array($result);
return $var;

dumpfi
08-13-2008, 09:29 AM
I haven't tested it, but I think your script hangs because arguments in PHP are passed by value.

Thus, when you call getResult($result), getResult gets a copy of $result and pg_fetch_array operates on this copy. Any changes it does to the internal structure of $result are not propagated back to the original. So, with the next iteration pg_fetch_array returns the same row again because it gets another copy of the unchanged original.

Try to change getResult to this
function getRows(&$result){
return pg_fetch_array($result);
}and see if it helps.

dumpfi



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum