Search code examples
phparraysreadline

Adding looped data into associative array with readline


Writing a small program to ask some people their dreams for fun. I'm trying to put the data into an associative array. I want it to come out like this (for example three names:

How many people should I ask their dreams?
*number*
What is your name?
*name*
What is your dream?
*dream*

name's dream is: dream

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;
        $dreams[] = readline() . PHP_EOL;
        echo "What is your dream?" . PHP_EOL;
        $dreams[] = readline() . PHP_EOL;
    }
    echo "In jouw bucketlist staat: " . PHP_EOL;
    foreach ($dreams as $key => $value) {
        echo $key . "'s dream is: " . $value;
    }
} else {
    exit($hoeveel . ' is geen getal, probeer het opnieuw');
}
?>

It keeps returning this:

0's dream is: *name*
1's dream is: *name*
etcetera.

Solution

  • When you read values from the $dreams array with foreach ($dreams as $key => $value), you're expecting names as keys, but that's not how you inserted the values. You can use the name as the array key like this instead:

    for ($i = 1; $i <= $many; $i++) {
        echo "What is your name?" . PHP_EOL;
    
        // set a name variable here
        $name = readline() . PHP_EOL;
        echo "What is your dream?" . PHP_EOL;
    
        // then use that variable as the array key here
        $dreams[$name] = readline() . PHP_EOL;
    }