The mysqli_fetch_array() function in PHP is used to fetch a result row as an associative, a numeric array, or both from a MySQLi query result.
Syntax
mysqli_fetch_array(result, resulttype)
- result: Required. The
mysqli_resultobject from amysqli_query(). - resulttype: Optional. Specifies what kind of array to return:
MYSQLI_ASSOC– Associative array (column names as keys)MYSQLI_NUM– Numeric array (column numbers as keys)MYSQLI_BOTH(default) – Both associative and numeric
Example with MYSQLI_BOTH (Default)
<?php
$conn = mysqli_connect("localhost", "root", "", "test_db");
$result = mysqli_query($conn, "SELECT id, name FROM users");
while ($row = mysqli_fetch_array($result)) {
echo $row[0] . " - " . $row['name'] . "<br>";
}
?>
Output:
1 - John
2 - Alice
3 - Bob
In the above:
$row[0]uses numeric index (id)$row['name']uses associative index
Example with MYSQLI_ASSOC
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo $row['id'] . " - " . $row['name'] . "<br>";
}
Here, only associative keys are used. $row[0] would throw an error.
Example with MYSQLI_NUM
while ($row = mysqli_fetch_array($result, MYSQLI_NUM)) {
echo $row[0] . " - " . $row[1] . "<br>";
}
Here, only numeric indexes are used. $row['name'] would throw an error.
Important Notes:
mysqli_fetch_array()returnsfalsewhen there are no more rows.- If using
MYSQLI_BOTH, each field is available in two ways (by name and by number), which can use more memory.
0
likes
Your Feedback
Help us improve by sharing your thoughts
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
