Jump to content


Photo

Easiest way to echo an array


  • Please log in to reply
4 replies to this topic

#1 ldsmike88

ldsmike88
  • Members
  • PipPipPip
  • Advanced Member
  • 168 posts
  • LocationFlorida

Posted 30 May 2006 - 03:08 AM

What is the easiest way to echo an array in a format like this:
"2001", "2002", "2003", "2004"

I can echo an array like this:
foreach($exedYear as $exedYearValue){
echo '"' . $exedYearValue . '", ';
}

But then at the end of the array there is an extra comma and space. How do I get rid of the comma? Thanks!

Mike

#2 Ferenc

Ferenc
  • Members
  • PipPipPip
  • Advanced Member
  • 94 posts

Posted 30 May 2006 - 04:38 AM

[!--quoteo(post=378280:date=May 29 2006, 09:08 PM:name=ldsmike88)--][div class=\'quotetop\']QUOTE(ldsmike88 @ May 29 2006, 09:08 PM) View Post[/div][div class=\'quotemain\'][!--quotec--]
What is the easiest way to echo an array in a format like this:
"2001", "2002", "2003", "2004"

I can echo an array like this:
foreach($exedYear as $exedYearValue){
echo '"' . $exedYearValue . '", ';
}

But then at the end of the array there is an extra comma and space. How do I get rid of the comma? Thanks!

Mike
[/quote]
explode() will do that for you.

$parts = explode(',', $exedYear);
foreach($parts as $key => $value){
echo trim($value) . "<br>";
}
Everything you want to know is here.

#3 poirot

poirot
  • Members
  • PipPipPip
  • Advanced Member
  • 646 posts
  • LocationAustin, TX

Posted 30 May 2006 - 04:43 AM

Ferenc, I guess you misunderstood him. He wants to output an array and not convert an array into a string.

You can use implode for that:
[a href=\"http://www.php.net/implode\" target=\"_blank\"]http://www.php.net/implode[/a]

echo implode(', ', $exedYear);

~ D Kuang

#4 Ferenc

Ferenc
  • Members
  • PipPipPip
  • Advanced Member
  • 94 posts

Posted 30 May 2006 - 04:50 AM



I assumed the array was
array(
[0] => "2001", "2002", "2003", "2004"
)
Everything you want to know is here.

#5 ldsmike88

ldsmike88
  • Members
  • PipPipPip
  • Advanced Member
  • 168 posts
  • LocationFlorida

Posted 30 May 2006 - 05:11 AM

That's interesting. I have been using explode() in this script but never implode. The only problem with that though is that it doesn't include the parenthases around the variables. I tried to add them but it doesn't set the new variables, it jecho's the same thing:
foreach($exedYear as $years){
$years = '"' . $years . '"';
}
echo implode(', ', $exedYear);

I got it!

echo '"' . implode('", "', $exedYear) . '"';

Thanks!




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users