30 September 2009 ~ 2 Comments

I’m sure this is bad practice somehow

PHP

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:

  1. Well, yeah.
  2. 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.

2 Responses to “I’m sure this is bad practice somehow”

  1. Rich Estill 30 September 2009 at 7:30 pm Permalink

    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?

  2. Dan 9 October 2009 at 7:45 am Permalink

    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 giving up foreach.


Leave a Reply