Jump to content

Multi dimensional array basic question


JakeMogul

Recommended Posts

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!?

Link to comment
Share on other sites

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].

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.