array with variable index: my_array[$i]

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
dsdsdsdsd
Forum Commoner
Posts: 60
Joined: Fri Dec 05, 2003 3:10 pm

array with variable index: my_array[$i]

Post by dsdsdsdsd »

hello;
this works:

Code: Select all

<?php
for ($i = 0 ; $i < count($item_array) ; $i++)
  { $item_parsed_array = explode("=" , $item_array[$i]);
     print("$item_parsed_array[0]<br>$item_parsed_array[1]<p>");  
?>
however this does not:

Code: Select all

<?php
for ($i = 0 ; $i < count($item_array) ; $i++)
  { $item_parsed_array[$i] = explode("=" , $item_array[$i]);
     print("$item_parsed_array[$i][0]<br>$item_parsed_array[$i][1]<p>");  
?>
my conclusion is that I cannot index an array with a variable; any thoughts?

thank you
Shannon Burnett
Asheville NC USA, where the snow don't stick
User avatar
Sevengraff
Forum Contributor
Posts: 232
Joined: Thu Apr 25, 2002 9:34 pm
Location: California USA
Contact:

Post by Sevengraff »

It is totally possible to use variables as array indexs.
Have you tried useing foreach()?

Code: Select all

<?php
foreach( $item_array as $key => $value )
{
    $item_parsed_array[$key] = explode('=', $value);
}
print_r( $item_parsed_array );

?>
dsdsdsdsd
Forum Commoner
Posts: 60
Joined: Fri Dec 05, 2003 3:10 pm

Post by dsdsdsdsd »

hello sevengraff; thanks for the response;
I have not tried any other loops; however I have finally gotten the solution; the problem is have a variable index WITHIN a print statement;
Solution: curly brackets;

Code: Select all

<?php
for ($i = 0 ; $i < count($item_array) ; $i++)
  { $item_parsed_array[$i] = explode("=" , $item_array[$i]);
    print("{$item_parsed_array[$i][0]}<br>{$item_parsed_array[$i][1]}<p>");  
  }
?>
thanks
Shannon
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post by twigletmac »

Formatting your code and removing uneccessary characters (such as parenthesis around print() statements), can make things somewhat easier to debug:

Code: Select all

<?php
for ($i = 0 ; $i < count($item_array) ; $i++)
  {
    $item_parsed_array[$i] = explode("=" , $item_array[$i]);
   print "{$item_parsed_array[$i][0]}<br>{$item_parsed_array[$i][1]}<p>"; 
  }
?>
If you are using a syntax highlighter, you can make the variables stand out by using concenation:

Code: Select all

print $item_parsed_array[$i][0].'<br />'.$item_parsed_array[$i][1].'<p>';
Mac
Post Reply