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

 

 

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, ',');

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! =)

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]

 

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.