0

I'm trying to create a simple 2D array in PHP and it doesn't seem to work as described. For instance, I tried the sample code from the w3schools.com site:

$cars = array
  (
  array("Volvo",100,96),
  array("BMW",60,59),
  array("Toyota",110,100)
  );

But when I call:

 echo "$cars[1][1]";

it outputs "Array[1]", not "60". As far as I can tell, the only thing that's getting stored is the string "Array". It doesn't matter how big or small the array is or what method I declare it in or whether it's string or integer, etc... it doesn't actually store the proper data in any sort of array format.

5
  • Works for me - phpFiddle Commented Sep 5, 2013 at 23:57
  • Remove the quotes in your echo Commented Sep 5, 2013 at 23:59
  • 3
    It won't expand a value from a multi-dimensional array in a double-quoted string like that. You need either echo "{$cars[1][1]}" (curly brackets) or just drop the quotes altogether, since they aren't needed: echo $cars[1][1]. What it's actually doing there is the equivalent of echo $cars[1] . "[1]" Commented Sep 5, 2013 at 23:59
  • Ah, thanks! Normal one-dimensional arrays work just fine in double-quoted strings, so it didn't occur to me it that that could be the problem. Commented Sep 6, 2013 at 0:04
  • 1
    w3schools is bad and you should feel bad... Commented Sep 6, 2013 at 0:07

1 Answer 1

2

Your problem is in the way you're echoing the element.

echo $cars[1][1];    //60 

You're using quotes around your variable:

echo "$cars[1][1]"; // Array[1]

You can include your array in a quoted string if you use curly braces:

echo "{$cars[1][1]}";    // 60
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.