Concactenating an array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
greyhoundcode
Forum Regular
Posts: 613
Joined: Mon Feb 11, 2008 4:22 am

Concactenating an array

Post 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.
frao_0
Forum Commoner
Posts: 27
Joined: Sat Aug 08, 2009 3:52 am
Location: Toulouse, France

Re: Concactenating an array

Post 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.
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Re: Concactenating an array

Post by VladSun »

There are 10 types of people in this world, those who understand binary and those who don't
SidewinderX
Forum Contributor
Posts: 407
Joined: Fri Jul 16, 2004 9:04 pm
Location: NY

Re: Concactenating an array

Post by SidewinderX »

Is there something wrong with

Code: Select all

$myArray[0] . "-" . $myArray[1]
User avatar
greyhoundcode
Forum Regular
Posts: 613
Joined: Mon Feb 11, 2008 4:22 am

Re: Concactenating an array

Post 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.
Post Reply