Jump to Content
Jump to Navigation

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:

  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 Says:

    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 Says:

    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.


Leave me your comments

Enter Your Details:


You may write the following basic XHTML Strict in your comments:
<a href="" title=""></a> <abbr title=""></abbr> <dfn title=""></dfn> <q></q>
<blockquote cite=""></blockquote> <cite></cite> <code></code> <kbd></kbd> <strong></strong> <em></em>

  • Your mature and responsible replies are greatly appreciated by all. Thank you.
Enter Your Comments: