Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output (echo/print) everything from a PHP Array

Tags:

Is it possible to echo or print the entire contents of an array without specifying which part of the array?

The scenario: I am trying to echo everything from:

while($row = mysql_fetch_array($result)){ echo $row['id']; } 

Without specifying "id" and instead outputting the complete contents of the array.

like image 360
nickcharlton Avatar asked Mar 28 '09 22:03

nickcharlton


People also ask

How do I echo an entire array?

To echo an array, use the format echo ${Array[0]}. Array is your array name, and 0 is the index or the key if you are echoing an associative array. You can also use @ or * symbols instead of an index to print the entire array.


2 Answers

If you want to format the output on your own, simply add another loop (foreach) to iterate through the contents of the current row:

while ($row = mysql_fetch_array($result)) {     foreach ($row as $columnName => $columnData) {         echo 'Column name: ' . $columnName . ' Column data: ' . $columnData . '<br />';     } } 

Or if you don't care about the formatting, use the print_r function recommended in the previous answers.

while ($row = mysql_fetch_array($result)) {     echo '<pre>';     print_r ($row);     echo '</pre>'; } 

print_r() prints only the keys and values of the array, opposed to var_dump() whichs also prints the types of the data in the array, i.e. String, int, double, and so on. If you do care about the data types - use var_dump() over print_r().

like image 136
Björn Avatar answered Sep 23 '22 11:09

Björn


For nice & readable results, use this:

function printVar($var) {     echo '<pre>';     var_dump($var);      echo '</pre>'; } 

The above function will preserve the original formatting, making it (more)readable in a web browser.

like image 43
karim79 Avatar answered Sep 21 '22 11:09

karim79