View Single Post
Old 10-05-2012, 01:59 PM   PM User | #1
Banjo
New to the CF scene

 
Join Date: Sep 2012
Posts: 3
Thanks: 1
Thanked 0 Times in 0 Posts
Banjo is an unknown quantity at this point
Simplify array to string

Hello all,

I have an array like this:

PHP Code:
$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

PHP Code:
$people = array('Alan''Steve'); 
it would output

"Alan and Steve"


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

PHP Code:
<?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
Banjo is offline   Reply With Quote