...

View Full Version : Simplify array to string



Banjo
10-05-2012, 02:59 PM
Hello all,

I have an array like this:


$people = array('Alan', 'Steve', 'John', 'Darren');

I was just wondering how I would be able to format that so it looked like this:

"Alan, Steve, John and Darren"

or if the array was this


$people = array('Alan', 'Steve');

it would output

"Alan and Steve"


So I wrote some code that would do this which is this:



<?php

$people = array('Alan', 'Steve', 'John', 'Darren');

$final_string = '';

for($i=0; $i < count($people); ++$i)
{
if($i === count($people) - 1)
{
$final_string .= " and " $people[$i];
}
else
{
if($i === 0)
{
$final_string .= $people[$i];
}
else
{
$final_string .= ", " . $people[$i];
}
}
}

?>



I'm just wondering if there is a better way to do this. Any help is appreciated, thank you for your time

- Ben

Fou-Lu
10-05-2012, 03:23 PM
function joinNames(array $aNames)
{
$sResult = array_pop($aNames);
if (!empty($aNames))
{
$sResult = implode(', ', $aNames) . ' and ' . $sResult;
}
return $sResult;
}

print joinNames($people);

Banjo
10-06-2012, 04:44 AM
Thank you very much, works a treat!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum