Display PHP Array as Table

The array_to_table function here takes a one-dimensional PHP array and turns it into a nicely formatted HTML table for display on your site.

There are a few options that you can pass in through the $args array:

  • class – If set, this will be the CSS class of the table itself.
  • custom_headers – If this array is present, it will replace the headers found in the $data array.
  • capitalize_headers – If TRUE, ucwords will be applied to all headers not affected by custom_headers.
  • format_functions – An optional array. With this, you can specify the name of a function to clean up the data in a particular column.
  • column_widths – Optional array that allows you to specific widths (in pixels) for each of the columns.
  • nowrap_head – If TRUE, nowrap will be added to the table header row cells.
  • nowrap_body – If TRUE, nowrap will be added to the table body cells.

Now, here's the function itself:

<?php

// Array to Table Function
// Copyright (c) 2014, Ink Plant
// https://inkplant.com/code/array-to-table

function array_to_table($data,$args=false) {
	if (!is_array($args)) { $args = array(); }
	foreach (array('class','column_widths','custom_headers','format_functions','nowrap_head','nowrap_body','capitalize_headers') as $key) {
		if (array_key_exists($key,$args)) { $$key = $args[$key]; } else { $$key = false; }
	}
	if ($class) { $class = ' class="'.$class.'"'; } else { $class = ''; }
	if (!is_array($column_widths)) { $column_widths = array(); }

	//get rid of headers row, if it exists (headers should exist as keys)
	if (array_key_exists('headers',$data)) { unset($data['headers']); }

	$t = '<table'.$class.'>';
	$i = 0;
	foreach ($data as $row) {
		$i++;
		//display headers
		if ($i == 1) { 
			foreach ($row as $key => $value) {
				if (array_key_exists($key,$column_widths)) { $style = ' style="width:'.$column_widths[$key].'px;"'; } else { $style = ''; }
				$t .= '<col'.$style.' />';
			}
			$t .= '<thead><tr>';
			foreach ($row as $key => $value) {
				if (is_array($custom_headers) && array_key_exists($key,$custom_headers) && ($custom_headers[$key])) { $header = $custom_headers[$key]; }
				elseif ($capitalize_headers) { $header = ucwords($key); }
				else { $header = $key; }
				if ($nowrap_head) { $nowrap = ' nowrap'; } else { $nowrap = ''; }
				$t .= '<td'.$nowrap.'>'.$header.'</td>';
			}
			$t .= '</tr></thead>';
		}

		//display values
		if ($i == 1) { $t .= '<tbody>'; }
		$t .= '<tr>';
		foreach ($row as $key => $value) {
			if (is_array($format_functions) && array_key_exists($key,$format_functions) && ($format_functions[$key])) {
				$function = $format_functions[$key];
				if (!function_exists($function)) { custom_die('Data format function does not exist: '.htmlspecialchars($function)); }
				$value = $function($value);
			}
			if ($nowrap_body) { $nowrap = ' nowrap'; } else { $nowrap = ''; }
			$t .= '<td'.$nowrap.'>'.$value.'</td>';
		}
		$t .= '</tr>';
	}
	$t .= '</tbody>';
	$t .= '</table>';
	return $t;
}

?>

So you can see how it works, we'll start with an example array of 2013 population estimates from the U.S. Census Bureau generated in our CSV to PHP Array article and then print it out as a table.

<?php

//set the location of your CSV file
$file = HOME_DIR.'inkplant.com/population.csv'; 

//turn that CSV file into an array ( see https://inkplant.com/aanoi/inkplant.com/code/csv-to-array )
$data = csv_to_array($file,true);

//set options for your table
$args = array(
  'class'=>'standard smalltext',
  'column_widths'=>array(
	'SUMLEV'=>75,
	'REGION'=>75,
	'DIVISION'=>75
  ),
  'custom_headers'=>array(
	'DIVISION'=>'Division',
	'POPEST18PLUS2013'=>'18+ Population<br />Estimate, 2013'
  ),
  'format_functions'=>array(
	'POPESTIMATE2013'=>'number_format',
	'PCNT_POPEST18PLUS'=>'format_percent'
  )
);

//remove all but the 50 states
unset($data['2']); //U.S. total
unset($data['11']); //Washington, D.C.
unset($data['54']); //Puerto Rico

//only show states with over 10 million people
foreach ($data as $i => $item) {
	if ($item['POPESTIMATE2013'] < 10000000) { unset($data[$i]); }
}

//display table
echo array_to_table($data,$args);

//function to format percent
function format_percent($value) {
	return number_format($value,1).'%';
}


?>

Here's that output. Note that the column headers for two of the columns have been cleaned up using the custom_headers option. Also, two of the columns have their data being cleaned by functions specified in the format_functions option. number_format is a built-in PHP function, so we didn't have to define it like we did format_percent.

SUMLEVREGIONDivisionSTATENAMEPOPESTIMATE201318+ Population
Estimate, 2013
PCNT_POPEST18PLUS
40496California38,332,5212915764476.1%
403512Florida19,552,8601552618679.4%
402317Illinois12,882,135985882876.5%
401236New York19,651,1271541115178.4%
402339Ohio11,570,808892097877.1%
401242Pennsylvania12,773,8011005815678.7%
403748Texas26,448,1931940620773.4%

I've also published an array to chart function that operates on the same principal, but gives you a colorful chart rather than a data table. Paired with each other, these two functions can quickly and easily let you display your data in an attractive and easy to understand fashion.


Comments

Loading…

This post was first published on August 8th, 2014 and last updated on November 6th, 2014 by Robert James Reese in PHP. Before using any of the code or other content in this post, you must read and agree to our terms of use.