Skip to content
Advertisement

Adding values to multidimensional array PHP without overwritting last added value

I’m having trouble with adding values to an associative multidimensional array and echoing them out. The last value added is the one being echoed out. I tried playing with $j next to $dreams[$name] but then it only echoes out the first letter. My code is as follows:

<?php
echo "How many people should I ask their dreams?" . PHP_EOL;
$many = readline();
$dreams = [];

if (is_numeric($many)) {
    for ($i = 1; $i <= $many; $i++) {
        echo "What is your name?" . PHP_EOL;
        $name = readline();
        echo "How many dreams are you going to enter?" . PHP_EOL;
        $numberDreams = readline();
        if (is_numeric($numberDreams)) {
            for ($j = 1; $j <= $numberDreams; $j++) { 
                echo "What is your dream?" . PHP_EOL;
                $dreams[$name] = readline();
            }
        }
    }
    echo "In jouw bucketlist staat: " . PHP_EOL;
    foreach ($dreams as $key => $value) {
        echo $key . "'s dream is: " . $value . PHP_EOL;
    }
} else {
    exit($many . ' is not a number, try again.');
}
?>

Advertisement

Answer

You need

$dreams[$name][] = readLine();

This creates a new array entry within $dreams[$name] for each entered value. Otherwise yes you’re overwriting $dreams[$name] every time with a different value.

And then to output, you’ll need two loops, one for the names and one for the dreams – it should be a mirror of the input process – because effectively you’re doing the process in reverse, with the same data structure:

foreach ($dreams as $name => $entries) {
    echo $name . "'s dreams are: ". PHP_EOL;
    
    foreach ($entries as $dream)
    {
      echo $dream.PHP_EOL;
    }
}

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement