Jaguar Posted July 1, 2008 Share Posted July 1, 2008 $count = 1; while($row = mysql_fetch_assoc($result)) { if(mysql_num_rows($result) == $count)) { $site_title = $row['title']; } // other code here $count++; } Is there a better way to do this without using a count variable? I don't want the title variable to get assigned for every loop, I just want it to be assigned once. Quote Link to comment https://forums.phpfreaks.com/topic/112810-how-to-check-if-loop-is-at-the-last-or-first-mysql-row-result/ Share on other sites More sharing options...
BlueSkyIS Posted July 1, 2008 Share Posted July 1, 2008 that won't work as you might expect it to. you'll want to use something more like this: $count = 1; while($row = mysql_fetch_assoc($result)) { if($count == 1) { $site_title = $row['title']; } // other code here $count++; } Quote Link to comment https://forums.phpfreaks.com/topic/112810-how-to-check-if-loop-is-at-the-last-or-first-mysql-row-result/#findComment-579422 Share on other sites More sharing options...
Jaguar Posted July 1, 2008 Author Share Posted July 1, 2008 A better way than that would be... $count = 1; while($row = mysql_fetch_assoc($result)) { if($count == 1) { $site_title = $row['title']; $count++; } // other code here } I was trying to avoid creating a variable. I was hoping there was a way to use functions something like... if(mysql_num_rows($result) == function_that_checks_what_number_row_this_is($row)) { $site_title = $row['title']; } Quote Link to comment https://forums.phpfreaks.com/topic/112810-how-to-check-if-loop-is-at-the-last-or-first-mysql-row-result/#findComment-579456 Share on other sites More sharing options...
.josh Posted July 1, 2008 Share Posted July 1, 2008 Why don't you want the title to be assigned every time? Does that value change? Worried about performance? Only other way is to make a condition. But since the condition will be checked every single iteration...you really aren't saving on performance; you're just trading one thing for the other. But nonetheless, you can simply just check to see if $site_title exists inside your condition: while($row = mysql_fetch_assoc($result)) { if (!$site_title) $site_title = $row['title']; // other code here } Quote Link to comment https://forums.phpfreaks.com/topic/112810-how-to-check-if-loop-is-at-the-last-or-first-mysql-row-result/#findComment-579459 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.