John Davidson

Adding values to multidimensional array PHP without overwritting last added value

0 comments
Message:


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


My Answer:
php
$dreams = array();

$name = "Alice";
$dreams[$name][] = "Flying";
$dreams[$name][] = "Exploring";

$name = "Bob";
$dreams[$name][] = "Swimming";
$dreams[$name][] = "Reading";

foreach ($dreams as $name => $dream) {
echo $name . "'s dreams: ";
foreach ($dream as $value) {
echo $value . ", ";
}
echo "
";
}


In this code, I am creating an associative multidimensional array `$dreams` where the key is the person's name and the value is an array of their dreams. By using the `[]` operator, I am adding values to the array without overwriting the previously added values.

When echoing out the values, I use a nested foreach loop to iterate over each person's dreams and display them. This way, all the dreams for each person are echoed out correctly without overwriting the last added value.

Rate this post

4 of 5 based on 7874 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us