I was wondering if its possible to use the result of a simple arithmetic equation as the index into an array e.g //Load Array $Arr[]="Tom"; $Arr[]="Sarah"; $Arr[]="Paul"; $Arr[]="John"; //Display Array for ($i=0;$i<=4;$i++) { //Is it possible to do the following print "Arr[1] is related to Arr[$i+2]";
/* I want it to display Sarah is related to John but I get an error saying missing "[ " in the print line. As far as I can remember its possible to do the above in C++ }
it should work; could the problem be missing dollars?
print "Arr[1] is related to Arr[$i+2]"; >> print "$Arr[1] is related to $Arr[$i+2]";
i'd be inclined to cat them into the string, too..
print $Arr[1]." is related to ".Arr[$i+2];
-- rad
I may have typed my example incorrectly but the error I get is not related to missing dollar signs. I get an error msg about missing square brackets .The work around I used was to do the arithmetic before the array access and then reassign the index variable I used if I needed to access the array again heres a very basic e.g //Start $i=1+2; $Arr[]="Tom"; $Arr[]="Sarah"; $Arr[]="Paul"; $Arr[]="Sam";
print" $Arr[2] is related to $Arr[$i]"; //results in Paul is related to Sam Do you think the concatenate op would work better? Thanks for the help
Yes. In string,s PHP does not allow you to use a var in the brackets of an array.
this works fine:
print" $Arr[2] is related to ".$Arr[$i]."\n";