Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New to the CF scene
    Join Date
    Sep 2012
    Posts
    3
    Thanks
    1
    Thanked 0 Times in 0 Posts

    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

  • #2
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,978
    Thanks
    4
    Thanked 2,659 Times in 2,628 Posts
    PHP Code:

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

    print 
    joinNames($people); 

  • Users who have thanked Fou-Lu for this post:

    Banjo (10-06-2012)

  • #3
    New to the CF scene
    Join Date
    Sep 2012
    Posts
    3
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Thank you very much, works a treat!


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •