Page 1 of 1

array with variable index: my_array[$i]

Posted: Fri Dec 19, 2003 5:42 pm
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

Posted: Fri Dec 19, 2003 5:52 pm
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 );

?>

Posted: Fri Dec 19, 2003 5:56 pm
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

Posted: Mon Dec 22, 2003 5:03 am
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