Some help with PHP arrays...

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
philsbury
Forum Newbie
Posts: 4
Joined: Fri Jan 02, 2009 6:21 pm

Some help with PHP arrays...

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

Re: Some help with PHP arrays...

Post by VladSun »

Code: Select all

foreach ($array as $key => $value)
    for ($i=0; $i<$value; $i++)
        echo $key.", ";
There are 10 types of people in this world, those who understand binary and those who don't
philsbury
Forum Newbie
Posts: 4
Joined: Fri Jan 02, 2009 6:21 pm

Re: Some help with PHP arrays...

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

Re: Some help with PHP arrays...

Post 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 ;)
There are 10 types of people in this world, those who understand binary and those who don't
philsbury
Forum Newbie
Posts: 4
Joined: Fri Jan 02, 2009 6:21 pm

Re: Some help with PHP arrays...

Post 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:
philsbury
Forum Newbie
Posts: 4
Joined: Fri Jan 02, 2009 6:21 pm

Re: Some help with PHP arrays...

Post 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);
Post Reply