Page 1 of 1

Some help with PHP arrays...

Posted: Fri Jan 02, 2009 6:22 pm
by philsbury
Hi,

I need a bit of help with an array. I'm posting quantities through a form and picking it up as an array which when printed looks like this:
Array ( [item1] => 4 [item2] => 1 )

What I want to do is now extract that data and display it as a list similar to:
item1, item1, item1, item1, item2

Any ideas?

Thanks
Phil

Re: Some help with PHP arrays...

Posted: Fri Jan 02, 2009 6:35 pm
by VladSun

Code: Select all

foreach ($array as $key => $value)
    for ($i=0; $i<$value; $i++)
        echo $key.", ";

Re: Some help with PHP arrays...

Posted: Fri Jan 02, 2009 6:41 pm
by philsbury
Thanks this almost does exactly what I want, though is there a way to not have the final comma?

item1, item1, item1, item1, item2, to item1, item1, item1, item1, item2

picky I know!

Cheers
Phil

Re: Some help with PHP arrays...

Posted: Fri Jan 02, 2009 6:44 pm
by VladSun
philsbury wrote:Thanks this almost does exactly what I want, though is there a way to not have the final comma?
:)
I knew you were going to say that - it's your homework ;)

Re: Some help with PHP arrays...

Posted: Fri Jan 02, 2009 6:47 pm
by philsbury
:) homework complete, though a slight variation:

Code: Select all

$str = "";
    foreach($array as $key => $value)
    {
        $str .= str_repeat($key.",", $value);
    }
    $str = substr($str, 0, strlen($str) - 2);
    echo $str;
Thanks for your help! :mrgreen:

Re: Some help with PHP arrays...

Posted: Fri Jan 02, 2009 6:57 pm
by philsbury
no, thats not right, should be -1:

Code: Select all

$str = "";
    foreach($array as $key => $value)
    {
        $str .= str_repeat($key.",", $value);
    }
    $str = substr($str, 0, strlen($str) - 1);