Jump to content

Archived

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

jonrick

Simple Array Help!

Recommended Posts

I'm more or less trying to get $items[$i] to equal $item_nameX with X being $i. If you look at the code you should be able to understand what I'm trying to do.

<?PHP
$item_name1 = "Armor";
$item_name2 = "Pants";
$item_name3 = "Gloves";
$item_name4 = "Helmet";
$item_name5 = "Shield";
$num_cart = 5 +1;

for ($i=1; $i < $num_cart; $i++)
{
[color=red]/*********************************
All I need this line of code todo
is for $items[$i] = $item_name$i
*********************************/
[b]$items[$i] = `echo \$item_name$i`;[/b][/color]
}

$num = count($items);
$num = $num -1;

for ($i=1; $i < $num_cart; $i++)
{
echo $items[$i];
echo '<br>';
}


?>

Share this post


Link to post
Share on other sites
Try this:
[code]<?PHP
$item_name1 = "Armor";
$item_name2 = "Pants";
$item_name3 = "Gloves";
$item_name4 = "Helmet";
$item_name5 = "Shield";
$num_cart = 6;

for ($i=1; $i < $num_cart; $i++)
$items[] = ${'item_name'.$i}; // this is the line you're looking for -- it's using variable variables
echo implode('<br>',$items);
?>[/code]

Variable variables are explained in the manual: http://us3.php.net/manual/en/language.variables.variable.php

Ken

Share this post


Link to post
Share on other sites
Why not using
[code]$item_name1 = "Armor";
$item_name2 = "Pants";
$item_name3 = "Gloves";
$item_name4 = "Helmet";
$item_name5 = "Shield";[/code]

in array too ? And you can use count instead of typing all the total variable yourself.

Share this post


Link to post
Share on other sites

×

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.