Search code examples
phpmultidimensional-arrayassociative-array

How can I echo the right key in my multidimensional associative array?


My objective is to create a multidimensional associative array with friends and their dreams (user input) in it. I think (hope) that I can am close to finishing it, but I get an unwanted result when echoing the final step:

I am trying to echo a sentence including the name of a 'friend' on line 22. Instead of a name inputted by the user, I get 'Array' as a result. E.g.: Array has this as their dream: Climbing Mount Everest

Does anyone know how I get the name of the friend here?

A line/string should be echoed for every separate dream that was filled in. And I included the print function for my clarity, will delete later. Thanks!

<?php

$friends = readline('How many friends should we ask for their dreams? ');
$array = [];

if (is_numeric($friends) == false) {
    exit("This is not a number." . PHP_EOL);
} else if ($friends == 0) {
    exit("This is not valid input." . PHP_EOL);
} else {
    for ($i = 1; $i <= $friends; $i++) {
        $name_key = readline('What is your name? ');
        $number_dreams = readline('How many dreams are you going to enter? ');
        for ($x = 1; $x <= $number_dreams; $x++) {
            $dream_value = readline('What is your dream? ');
            $array[$name_key][] = $dream_value;
        }
        print_r($array);
    }
    foreach ($array as $friend) {
        foreach ($friend as $key => $value) {
            echo $friend . ' has this as their dream: ' . $value . PHP_EOL;
        }
    }
}

Solution

  • try this after you assembled $array:

    foreach ($array as $frndNm=>$dreams){ 
            foreach($dreams as $dream){ 
             echo( $frndNm.' dream is '.$dream); 
            } 
    }