Imploding Arrays

You want to convert an array to a string.

Use implode(). You pass the delimiter to separate each element.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="EN" lang="EN">
<head>
<title>PHP</title>
<meta Name="Author" Content="Hann So">
</head>
<body>
<p>
<?php
$fruits = array('Apples', 'Grapes', 'Bananas', 'Oranges');
print_r($fruits);
// use blank space as a delimiter
$fruits_string = implode(" ", $fruits);
echo "<p><b>Implode an asociated array.</b></p>";
echo $fruits_string;

echo "<p><b>This is an associated array.</b></p>";

$fruits = array('red'=>'Apples', 'green'=>'Grapes', 'yellow'=>'Bananas', 'orange'=>'Oranges');
print_r($fruits);
// use , as a delimiter
$fruits_string = implode(",", $fruits);
echo "<p><b>Implode an associated array.</b></p>";
echo $fruits_string;
?>
</p>
</body>
</html>

View the effect

You want to print out an array with commas separating the elements and with an "and" before the last element if there are more than two elements in the array.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="EN" lang="EN">
<head>
<title>PHP</title>
<meta Name="Author" Content="Hann So">
</head>
<body>
<p>
<?php
function pc_array_to_comma($array) {
// check the size of the array
switch (count($array)) {
	case 0:
		return "";
	case 1:
		return reset($array);
	case 2:
		return join(' and ', $array);
	default:
	    // get the last element
		$last = array_pop($array);
		return join(', ', $array).", and $last";
}
}

$fruits = array('Apples', 'Grapes', 'Bananas', 'Oranges');
print_r($fruits);
$fruits_new = pc_array_to_comma($fruits);

echo "<p><b>Print the array</b></p>";
echo $fruits_new;
?>
</p>
</body>
</html>

View the effect


Arrays (cintinued) | Adding all Values in an Array | Flipping an Array | Extracting Variables from Arrays | Imploding Arrays | Exploding Arrays | Navigating through Arrays | Merging Arrays | Comparing Arrays | Sorting Arrays | Creating Multidimensional Arrays | Sorting Multiple Arrays
© 2008: Hann So
email: hso@voyager.deanza.edu