I’m sure this is bad practice somehow
If you don’t know PHP, you can safely ignore this.
I had been using the following code to get rows out of a database (it’s with Oracle, but I’m sure mysql_fetch_assoc() would work just as well for these):
while ($row = oci_fetch_array($result)) {
$whatever[] = $row[];
}
But then it hit me: if I’m already fetching the next row of results in the while() statement, and only copying the results into another array, couldn’t I compact the code more? I rushed to that old sandbox of mine, test.php, and tried:
while ($whatever[] = oci_fetch_array($result));
And by gum, it worked.
I’m assuming there will be one of two reactions from people who read this far:
- Well, yeah.
- That’s horribly bad practice because…
But considering I’m entirely self-taught, I’m fairly proud of myself. And if I shouldn’t be, please do let me know.
Edit: And there it is! Since the loop creates the new item in the array and then fills it with the value of oci_fetch_array, there’s always an empty value at the end that messes with foreach(). It was a fun idea while it lasted, though.
September 30th, 2009 at 7:30 pm
Instead of the foreach, can you do a
for(i=0;i<sizeof($whatever)-1;i++)
to deal with the empty value.
A bigger question: What is the goal of the array you are creating? Can you just use the resulting array from the database without creating your own array?
October 9th, 2009 at 7:45 am
As far as I know (and it’d make me feel really silly if I was wrong) there’s no way to grab all of the results with Oracle; you have to go in row by row.
And the for loop works, yes, but since the code was to save me an extra few keystrokes some of the time (sometimes I give my own keys, make a multidimensional array, etc) it’s not worth givign up foreach for.