Go Back   CodingForums.com > :: Server side development > PHP

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
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
Old 10-05-2012, 02:23 PM   PM User | #2
Fou-Lu
God Emperor


 
Fou-Lu's Avatar
 
Join Date: Sep 2002
Location: Saskatoon, Saskatchewan
Posts: 15,650
Thanks: 4
Thanked 2,451 Times in 2,420 Posts
Fou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to all
PHP Code:

function joinNames(array $aNames)
{
    
$sResult array_pop($aNames);
    if (!empty(
$aNames))
    {
        
$sResult implode(', '$aNames) . ' and ' $sResult;
    }
    return 
$sResult;
}

print 
joinNames($people); 
Fou-Lu is offline   Reply With Quote
Users who have thanked Fou-Lu for this post:
Banjo (10-06-2012)
Old 10-06-2012, 03:44 AM   PM User | #3
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
Thank you very much, works a treat!
Banjo is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 03:40 PM.


Advertisement
Log in to turn off these ads.