Codecademy Forums

PHP Nested Arrays exercise

Code:

<?php namespace Codecademy;

$treasure_hunt = ["garbage", "cat", 99, ["soda can", 8, ":)", "sludge", ["stuff", "lint", ["GOLD!"], "cave", "bat", "scorpion"], "rock"], "glitter", "moonlight", 2.11];

// Write your code below:

Instructions: We’re going treasure hunting! Hidden within this terribly nested array is the string `"GOLD!"` . Your job is use `echo` to print it to the terminal. The trick: you must use array indexing to accomplish this goal. It’s up to you whether you do this in one step or break it down into multiple steps.

My answer: echo implode($treasure_hunt[3][4][2]);

Output: GOLD!

Codecademy says: Did you use `[0]` to access `"GOLD!"` within the final array?

Why my answer is wrong? Output is good.

Your solution yields a correct result :slight_smile:

It’s pretty hard to test user submissions automatically and that is why codecademy has to sometimes make certain assumptions. In the case of this exercise, no one predicted that you will use the implode method (it wasn’t introduced earlier in the course, right?).

Codecademy assumed that you will perform this operation using array indexing:

echo $treasure_hunt[3][4][2][0];

I will not report this as a bug because this is kind of emphasized in the instructions:

The trick: you must use array indexing to accomplish this goal.

4 Likes

Ok, implode method was introduce in previus chapters.


So is this all right? echo implode($treasure_hunt[3][4][2][0]); I also write this but it’s PHP Warning.


Wielkie dzięki za pomoc :slight_smile:

implode() converts an array to a string. Since the value at $treasure_hunt[3][4][2][0] is already the string "GOLD!", you get an error. Your first code using implode() works because it is converting the array ["GOLD!"] to the string "GOLD!".

3 Likes

Thank you very much :slight_smile:

1 Like