Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding array notation (specifically mysql_fetch_array and print_r)

Tags:

arrays

php

mysql

Do functions that print arrays all use the same notation to do so? What is the reasoning for one notation over another? I noticed when using PHP print_r to display an array compiled using mysql_fetch_array, the notation of the array is as follows:

Array ([column] => value [index] = value)

For example, if this is the table:

id fname lname
1 John Smith

Then the print_r output of mysql_fetch_array will be:

Array ([id] => 1 [0] => 1 [fname] => John [1] => John [lname] => Smith [2] => Smith)

What is the reason for this notation? Specifically, why does the value repeat? Isn't that redundant?

Also, can anybody recommend a good resource for a better conceptual understanding of arrays in general? Thanks!

like image 813
Joe M. Avatar asked Aug 08 '26 14:08

Joe M.


2 Answers

Associative arrays use strings for the index, numeric arrays use numbers.

mysql_fetch_array() creates an associative array containing numeric keys as well so that both may be used to access the array.

mysql_fetch_assoc() creates an array containing only the string indices.

mysql_fetch_row() creates an entirely numeric array, and is the fastest to execute of these functions.

like image 194
Paul Avatar answered Aug 10 '26 05:08

Paul


print_r & var_dump are for debugging by a developer only. Its syntax is not set in stone, and shouldn't be relied upon. The only thing that matters is that it's readable to the developer. Especially look at the source of a html document and you see a more structured formatting.

As for your second question: seems like you did a mysql_fetch_array() instead of mysql_fetch_row or mysq_fetch_assoc, see the manual pages for those functions.

As for sources to learn about arrays: have you tried the manual?

like image 39
Wrikken Avatar answered Aug 10 '26 06:08

Wrikken