Jump to content


Photo

Simple Array Help!


  • Please log in to reply
2 replies to this topic

#1 jonrick

jonrick
  • New Members
  • Pip
  • Newbie
  • 1 posts

Posted 07 July 2006 - 01:14 AM

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++)
{
/*********************************
All I need this line of code todo
is for $items[$i] = $item_name$i
*********************************/
$items[$i] = `echo \$item_name$i`;

}

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

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


?>

#2 kenrbnsn

kenrbnsn
  • Staff Alumni
  • Advanced Member
  • 8,235 posts
  • LocationHillsborough, NJ, USA

Posted 07 July 2006 - 01:23 AM

Try this:
<?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);
?>

Variable variables are explained in the manual: http://us3.php.net/m...es.variable.php

Ken

#3 hackerkts

hackerkts
  • Members
  • PipPipPip
  • Advanced Member
  • 593 posts
  • LocationSingapore
  • Age:18

Posted 07 July 2006 - 01:35 AM

Why not using
$item_name1 = "Armor";
$item_name2 = "Pants";
$item_name3 = "Gloves";
$item_name4 = "Helmet";
$item_name5 = "Shield";

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

Regards,
hackerkts

To be a coder, you must learn how to think and not to give up so easily.





0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users