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_result
object from a mysqli_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()
returns false
when 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.