0

Desired result: "My preferred salty food is the snack Rufles". I would like to echo the array "snack" inside the array "salty food" as a string:

$food = array(
    "salty food" => array(
        "snack" => array(
            0 => "Rufles",
            1 => "Generic"
        )
    )
);

echo "My prefered ";

foreach($food as $key => $value)     //salty food
    echo $key;

echo " is the ";

//--MY DOUBT IS HERE. DESIRED ECHO: "snack" (FROM THE DEEP ARRAY):
foreach($food as $key => $value)
    echo $key["snack"];

print_r($food["salty food"]["snack"][0]);     //Rufles
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Luciano Santos
  • 153
  • 2
  • 12
  • 1
    and what is the code output? – aidinMC Aug 23 '17 at 22:22
  • What should it print if the arrays have more than one element? – Barmar Aug 23 '17 at 22:24
  • Why are you using loops to print `salty food` and `snack`, but then hard-coding them in the `print_r()` at the end? – Barmar Aug 23 '17 at 22:29
  • Possible duplicate of [PHP How to access all elements of multidimensional array if no indexes are known?](https://stackoverflow.com/questions/6824788/php-how-to-access-all-elements-of-multidimensional-array-if-no-indexes-are-known) – mickmackusa Aug 23 '17 at 23:36

2 Answers2

1

Use nested loops:

echo "My preferred ";
foreach ($food as $type1 => $value1) {
    echo $type1;
    echo " is the ";
    foreach ($value1 as $type2 => $value2) {
        echo "$type2 $value2[0]";
    }
}

DEMO

Barmar
  • 741,623
  • 53
  • 500
  • 612
0

Should be ok

<?php 

    $food = array(
        "salty food" => array(
            "snack" => array(
                0 => "Rufles",
                1 => "Generic"
                )
            )
    );

    echo "My prefered ";

    foreach($food as $key1 => $value){
        echo $key1;    
        echo " is the ";        
        foreach($value as $key2 => $value){
            echo $key2." ";
        }        
    }    
    print_r($food["salty food"]["snack"][0]);


?>
Bart
  • 1,268
  • 2
  • 12
  • 14