Jump to content

Help converting an array into comma separated values


TheBrandon

Recommended Posts

Hello all,

 

I'm trying to get better at manipulating arrays and I'm stumped on this one.

 

What would be the most efficient way of converting an array such as this:

 

Array ( [3] => 3 [9] => 1 [15] => 9 )

 

Into this:

 

3,3,3,9,15,15,15,15,15,15,15,15,15

 

 

Link to comment
Share on other sites

It's probably not the most efficient way, but this works:

$input = array('3' => 3, '9' => 1, '15' => 9);

$str = '';

foreach($input as $key => $val)
{
for($i = 0; $i < $val; $i++)
{
	$str .= $key . ',';
}
}

$str = rtrim($str, ',');

 

EDIT: This is better:

$input = array('3' => 3, '9' => 1, '15' => 9);

$str = '';

foreach($input as $key => $val)
{
$str .= str_repeat($key . ',', $val);
}

$str = rtrim($str, ',');

Link to comment
Share on other sites

It's probably not the most efficient way, but this works:

$input = array('3' => 3, '9' => 1, '15' => 9);

$str = '';

foreach($input as $key => $val)
{
for($i = 0; $i < $val; $i++)
{
	$str .= $key . ',';
}
}

$str = rtrim($str, ',');

 

EDIT: This is better:

$input = array('3' => 3, '9' => 1, '15' => 9);

$str = '';

foreach($input as $key => $val)
{
$str .= str_repeat($key . ',', $val);
}

$str = rtrim($str, ',');

 

Oh okay, the first one is similar to what I was doing. I'll look into str_repeat, thanks a lot! =)

Link to comment
Share on other sites

It's hard to improve much on scootstah's solution. This is an alternate, using str_repeat. It could be faster, but if it is, you'd have to run it a million times before it'd make a noticeable difference :P

 

<?php

$array = array(3=>3,9=>1,15=>9);

$out = '';
foreach( $array as $val => $mult )
$out .= str_repeat("$val,", $mult);
$out = substr($out,0,-1);

echo $out;

?>

 

[edit] Ninja'd by scoot's edit [/edit]

Link to comment
Share on other sites

 

implode alone is capable of that? Could you show me an example of how to achieve this using implode? I've been trying to do it with a foreach loop.

 

Oh, I guess I should have examined the values more closely when I saw there were more values than array elements. No, implode() will not do that on its own.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.