PHP: Implode an array into a readable format.

Posted on January 9, 2012 by Jimmy K. in Tutorials.

I was recently asked to write a function that implodes a list of items in an array into a human-readable list. For example, [[0] => “Jimmy”, [1] => “Ryan”, [2] => “Ken”, [3] => “Barbie”] would become “Jimmy, Ryan, Ken and Barbie” and [[0] => “apple”, [1] => “banana”] would become “apple and banana”.

<?php

/* implode an array into a readable format. */
function jImplodeWordList($aValues) {

	if (sizeof($aValues) == 0) return "";
	if (sizeof($aValues) == 1) return $aValues[0];
	if (sizeof($aValues) == 2) return $aValues[0] . " and " . $aValues[1];

	$sReturn = "";

	for ($i = 0; $i < sizeof($aValues) - 1; $i++) {
		$sReturn .= (!empty($sReturn) ? ", " : "") . $aValues[$i];
	}

	$sReturn .= " and " . $aValues[sizeof($aValues) - 1];
	return $sReturn;

}

This function accepts an array of values and compiles the returned string depending on the number of items in the array. If three or more values are passed, the function returns “X, Y and Z”; if two values are passed, the function returns “X and Y”; and if only one value is passed, the function returns “X”.

Tags: , ,

 

Jimmy K. is a Chicago-based web developer who actively posts tutorials, articles and insights on his web development blog to help other programmers and developers.

You can find Jimmy on Google+ and Twitter.

 
 
 
 
 

If you like this, please leave a comment.

Name (required)
Email Address (required)
Website
Comments: