Page 1 of 1

Concactenating an array

Posted: Sun Aug 09, 2009 9:46 am
by greyhoundcode
Let's say I've got an array as follows:

Code: Select all

Array 
( 
    [0] => bananaboat 
    [1] => frederick
    [2] => lambda 
)
And I want to join them into a single string, using a hyphen as the glue. I know I can do the following:

Code: Select all

implode('-', $myArray);
But what if all I want to glue together are the first two elements? That is to say, so I end up with

bananaboat-frederick

as opposed to

bananaboat-frederick-lambda

Is there an elegant way of achieving this? My current solution involves a function that loops iterates through the array x times and returns the desired result, however I can't help but think it is somewhat clunky.

Re: Concactenating an array

Posted: Sun Aug 09, 2009 10:00 am
by frao_0
implode does not have the limit parameter like explode has. Something to put on the PHP wishlist for versions to come. 8)

Try this for your problem:

Code: Select all

$myArray=array('bananaboat','frederick','lambda');
 
echo implode('',explode('-', implode('-',$myArray), -1)).'-'.end($myArray);
Edit: hum, maybe i misunderstood your question :oops: . i though you wanted the first elements to be joined together and the last one to be separated by a dash. Ok, so for what you ask, a while or a for statement would not seem clumsy to me.

Re: Concactenating an array

Posted: Sun Aug 09, 2009 10:08 am
by VladSun

Re: Concactenating an array

Posted: Sun Aug 09, 2009 7:56 pm
by SidewinderX
Is there something wrong with

Code: Select all

$myArray[0] . "-" . $myArray[1]

Re: Concactenating an array

Posted: Sun Oct 04, 2009 9:14 am
by greyhoundcode
(a very late reply! ...)

Yes array_slice() is a real treat for my particular problem.

Admittedly my original post didn't go into too much detail, but the reason $data[0] . '-' . $data[1] was unsuitable for my needs was that I needed an offset.