Home > OS >  Adding values to multidimensional array PHP without overwritting last added value
Adding values to multidimensional array PHP without overwritting last added value

Time:04-01

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.');
}
?>

CodePudding user response:

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;
    }
}

CodePudding user response:

You can use array_push() function and you can replace this line $dreams[$name] = readline(); with array_push($dreams[$name], readline());

  • Related