Output (echo/print) everything from a PHP Array


Question

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.

1
22
3/28/2009 10:39:16 PM

Accepted Answer

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().

34
3/28/2009 10:32:29 PM

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.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon