as you must have guessed I'm new to php so please bear with me. At the moment I'm writing some server side scripting and while I've been at it one particular thing is bothering me lately. The situation is as follows. I have two arrays: one with elements and the other with keys (indices) for the elements of the first array. What bothers me is when I'm trying to output an element via double array variables in a string:
echo "$elements[$index[0]]";
I get "Parse error: syntax error, unexpected '[', expecting ']' in C:\xampp\htdocs\test1.php on line 5" error. However if only single array is used as in:
echo "$elements[0]";
It works just fine (outputs a).
I have searched the forums and found little help with this. Also read through What is the difference between single-quoted and double-quoted strings in PHP? played around with single and double quotations but with little success.
The workaround I'm using at the moment is that I'm saving the value from $index
array into a variable and using it as an index into the $elements
array:
$key = $index[0];
echo "$elements[$key]";
Works fine, bus feels like a level of indirection.
The code:
<?php
$elements = ["a", "b", "c"];
$index = [2 , 1 , 0];
echo "$elements[$index[0]]";
?>
Error:
Parse error: syntax error, unexpected '[', expecting ']' in C:\xampp\htdocs\test1.php on line 5
Thanks to anyone giving their time to read and answer this.
EDIT: Thank you all for the prompt replies. Now I see that I was too naive thinking that I can simulate my exact problem using a simple example. The actual code I'm dealing with is:
mysql_query( "INSERT INTO pics (filename, date) VALUES( $dirArray[$keys[$index]] , $timestamp )" )
or die(mysql_error());
The error:
Parse error: syntax error, unexpected '[', expecting ']' in C:\xampp\htdocs\dbsetup.php on line 47
The irony is also strong as I have created a level of indirection with my question trying to solve a level of indirection in the code :)