The function enables you to store the values as an associative array, a numerical array, or a combination of both. You can then manipulate the array as usual.”
Let us dive in.
The following snippet shows the procedural syntax for the mysqli_fetch_array function:
mysqli_fetch_array(mysqli_result $result, int $mode = MYSQLI_BOTH): array|null|false
The function parameters are as shown:
- result – this parameter allows you to specify the mysql_result object returned by the mysqli_query(), mysqli_store_result(), mysqli_stmt_get_result(), or mysqli_use_result() functions.
- mode – the mode parameter defines the type of array used to store the resulting values. Accepted values include:
- MYSQLI_ASSOC – associative array.
- MYSQLI_NUM – numerical array.
- MYSQLI_BOTH – a combination of the associative and numerical array.
The function will then return the array with the fetched rows. If there are no fetched rows, the function returns null or false on failure.
Let us discuss an example of using the mysqli_fetch_array() function. Start by creating a sample database, table, and data as shown in the query below:
The resulting table is as shown:
The following example shows how to use PHP mysqli_fetch_array function to return the rows from the table above as an array.
Start by creating a PHP file:
Edit the file:
Add the code as shown:
Finally, run the script with PHP:
This should return the rows as an associative array, also known as a dictionary in other programming languages.
NOTE: Note we are accessing the values of the dictionary using the row name (dictionary key).
An example output is as shown:
To return the values as a numerical array, we can use the query:
Similarly, the code above should return the rows as:
Finally, to get the results as both associative and numerical arrays.
In this article, you learned how to use the mysqli_fetch_array function in PHP to fetch the rows from a database as an array.
Thanks for reading!!!