JakeMogul Posted January 10, 2013 Share Posted January 10, 2013 Hi, I decided to learn PHP & MySQL from scratch with "PHP & MySQL in Easy Steps" by Mike McGrath. Page 35 is a tutorial on Describing Dimensions. I think I've done exactly what it says, but my output is weird. The php code I wrote: <?php $letters = array('A','B','C','D','E','F','G'); $numbers = array(1,2,3,4,5,6); $matrix = array('Letters'=> $letters,'Number'=> $numbers); echo "<p>Start: {$matrix['Letter'][0]}</p>"; foreach($matrix as $array => $list) { echo '<ul>'; foreach($list as $key => $value) {echo "<li>$array[$key]=$value";} echo '</ul>'; } ?> According to the book should display like this: Start: A - Letter [0] = A - Letter [1] = B - Letter [2] = C - Number[0] = 1 - Number[1] = 2 - Number[2] = 3 I've checked my code twice. And had a friend check it. Can't find a difference between the book and my code, yet mine appears like this: Start: L=A e=B t=C t=D e=E r=F s=G N=1 u=2 m=3 b=4 e=5 r=6 What's wrong with it!? Quote Link to comment https://forums.phpfreaks.com/topic/272966-multi-dimensional-array-basic-question/ Share on other sites More sharing options...
Jessica Posted January 10, 2013 Share Posted January 10, 2013 So the syntax is: foreach($array AS $key=>$value){... Your matrix array has a KEY of 'Letters' and a value of $letters. When you use array syntax on a string like 'Letters' you get the character at that point in the string (starting at 0). Try putting a space between $array and [$key]. Right now you're doing $array[$key] meaning the character at the key in that variable. You want to just echo the string that is $array and the string that is [$key]. Quote Link to comment https://forums.phpfreaks.com/topic/272966-multi-dimensional-array-basic-question/#findComment-1404756 Share on other sites More sharing options...
PFMaBiSmAd Posted January 10, 2013 Share Posted January 10, 2013 You are missing the {} in the following line that would cause the key/index name in $array to be literally output, instead of being treated as an array of characters - echo "<li>{$array}[$key]=$value"; Quote Link to comment https://forums.phpfreaks.com/topic/272966-multi-dimensional-array-basic-question/#findComment-1404757 Share on other sites More sharing options...
JakeMogul Posted January 10, 2013 Author Share Posted January 10, 2013 Thanks guys. Putting a space between $array and [$key] did the trick. Quote Link to comment https://forums.phpfreaks.com/topic/272966-multi-dimensional-array-basic-question/#findComment-1404760 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.