Defaults may be wrong…

Just a word of warning when using PHP and Mysql – if you’re trying to make efficient code and not utilizing all sort of frameworks and abstractions, you might be in for a small surprise in a default setting.

Usually is slightly lazy and often use the mysql_fetch_assoc function. It provides each row as an associative array, and is quite convenient to work with. Recently however while optimizing some code, I figured I’d switch to using mysql_fetch_array assuming it should be more efficient. The logic being that mapping hash keys to array values wouldn’t be needed and it should use less memory.

It wasn’t the case out of the box. Switching from mysql_fetch_assoc to mysql_fetch_array without doing anything else actually increases you memory use, and is probably slightly slower. By default mysql_fetch_array does not just provide the field values as array indexes, but still maintains the hash keys too.

If you only want the indexes in the returned rows, you need to add an extra parameter to the function stating this explicitly.

  $row = mysql_fetch_array($result, MYSQL_NUM);

I wonder why it was made so. It seems like an odd choice when mysql_fetch_assoc kan provide the row indexed with hash keys – The correct behavior for mysql_fetch_array (by default) ought to be to just return the array without the hashkeys – and have that option available if needed.

  • Daniel Von Fange

    mysql_fetch_row() does what you were expecting.

    And I agree, mysql_fetch_array() is confozeling.

  • Daniel Von Fange

    mysql_fetch_row() does what you were expecting.

    And I agree, mysql_fetch_array() is confozeling.

  • mysql_fetch_array returns the query as an indexed and associative array, Daniel is correct in saying mysql_fetch_row() is what you were expecting of it.