note 73064 added to function.print-r

From: Date: Wed, 07 Feb 2007 20:45:08 +0000
Subject: note 73064 added to function.print-r
Groups: php.notes 
Request: Send a blank email to php-notes+get-123093@lists.php.net to get a copy of this message
I've got four functions for printing arrays out in a readable fashion, I hope someone finds them useful. //prints an array in a HTML table. Top row is the keys. function table( $array ) { $array = array_values( $array ); $keys = array_keys( $array[0] ); echo '<table border="1"><tr>'; foreach( $keys as $key ) { echo '<td>'.$key.'</td>'; } echo '</tr>'; foreach( $array as $row ) { echo '<tr>'; foreach( $row as $value ) { echo '<td>'.$value.'</td>'; } echo '</tr>'; } echo '</table>'; } //print_r enclosed in a <pre>, except it will always print something, even if the variable is null, number 0 or false. It also lets you label the dump. function dump( $var, $label=null ) { if( $var === '' or $var === null or $var === 0 ) { var_dump( $var ); return; } echo '<pre style="text-align: left; font-size: 10px;">'; if( $label ) { echo $label."\n"; } print_r( $var ); echo '</pre>'; } //This one gives you output you can copy and paste back into your PHP code to recreate the array. function dump_array( $array, $tabs=1 ) { $html = "<pre style=\"text-align: left; font-size: 10px;\">array( \n"; foreach( $array as $key => $val ) { $html .= str_repeat( "\t", $tabs )."'$key' => "; if( is_array( $val ) ) { $html .= dump_array( $array, $tabs+1 ); } else { $html .= "'$val',\n"; } } $html .= ')</pre>'; return $html; } //just add header( 'content-type: application/vnd.ms-excel' ) and you've got an excel file. function excel( $array ) { $array = array_values( $array ); $keys = array_keys( $array[0] ); foreach( $keys as $key ) { echo $key."\t"; } echo "\n"; foreach( $array as $row ) { foreach( $row as $value ) { echo $value."\t"; } echo "\n"; } } ---- Server IP: 216.194.113.175 Probable Submitter: 66.65.96.69 ---- Manual Page -- http://www.php.net/manual/en/function.print-r.php Edit -- https://master.php.net/note/edit/73064 Del: integrated -- https://master.php.net/note/delete/73064/integrated Del: useless -- https://master.php.net/note/delete/73064/useless Del: bad code -- https://master.php.net/note/delete/73064/bad+code Del: spam -- https://master.php.net/note/delete/73064/spam Del: non-english -- https://master.php.net/note/delete/73064/non-english Del: in docs -- https://master.php.net/note/delete/73064/in+docs Del: other reasons-- https://master.php.net/note/delete/73064 Reject -- https://master.php.net/note/reject/73064 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#123093) next »