tags:

views:

2028

answers:

6

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  A: 

var_dump() can do it

Anonymous
+3  A: 

I think you are looking for print_r which will print out the array as text. You can't control the formatting though, it's more for debugging. If you want cool formatting you'll need to do it manually.

SoapBox
A: 

You can use print_r to get human-readable output.

See http://www.php.net/print_r

+3  A: 

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.

karim79
Shouldn't you call that printVar or debugVar? Why call it readVar?
jmucchiello
Good point, named it on the fly. Should probably be printVar. Thanks for the down-vote.
karim79
A: 

Similar to karim's, but with print_r which has a much small output and I find is usually all you need:

function PrintR($var) {
    echo '<pre>';
    print_r($var);
    echo '</pre>';
}
Darryl Hein
+4  A: 

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

Björn