Skip to content
PHP Logo

Is it better to use associative arrays instead of numeric arrays when fetching data in PHP?

When fetching data in PHP, associative arrays are generally better to use than numeric arrays because they allow you to access values by a specified key rather than relying on numerical indexes. This makes the code more readable, maintainable, and less error-prone, especially when dealing with large datasets where the order of elements may change.

php
// Using associative arrays to fetch data in PHP
$data = [
    'name' => 'John',
    'age' => 30,
    'city' => 'New York'
];

echo $data['name']; // Output: John
echo $data['age']; // Output: 30
echo $data['city']; // Output: New York