PHP MySql fetch_assoc Vs fetch_array Vs fetch_object performance difference

In this post we will see how these 3 main MySql data fetching methods in PHP performance.

In almost all php-mysql programming, you will need to fetch data from database to populate your applications with data.

There are 3 most popular methods of getting more than one data set when fetched.

mysql_fetch_assoc() : This function fetch an associative array of data.
mysql_fetch_array() : This function returns a combination array of associative elements as well as data with numerical index.
mysql_fetch_object() : This function returns an object with properties that correspond to the fetched row. 

Each data set contains a unique id element, int & a string element which makes it the normal set of values which is being retrieved in most normal cases.

The default functionality of mysql_fetch_assoc is running at a higher performance than the other 2 methods (mysql_fetch_array & mysql_fetch_object). mysql_fetch_object performance is justified as it returns objects instead of native arrays which will always bring in a better memory usages than any other kinds of output array. And for using the Object oriented result set approach the other 2 functions cannot satisfy. Lets take the case of mysql_fetch_array(); The problem here is in daily programming usages many php programmers have used the mysql_fetch_array() as such without going into the details of its usage. By default mysql_fetch_array returns 2 types of results sets as given by its default result_type value MYSQL_BOTH

result_type : MYSQL_NUM - which returns only a numbered index array eg: array([0]=>'mango')
result_type : MYSQL_ASSOC - which returns only associative array eg: array('car'=>'BMW') where 'car' will be the database column name or alias used.

So when use mysql_fetch_array, it returns duplicate set of data consisting of both numbered index as well as associative arrays which ofcourse is performance blocker.
So whenever you are using mysql_fetch_array function always specify the return_type of the result set array needed.
And in most cases we will need an associative array during iterative data management in php. so the best function to call will be mysql_fetch_assoc() as performance wise.

Happy Coding !! :)