Skip to content
PHP Logo

How can arrays be effectively integrated into existing PHP code to assign unique IDs to music titles for the play() function?

To assign unique IDs to music titles for the play() function, we can create an associative array where the keys are the unique IDs and the values are the music titles. We can then use this array to retrieve the title based on the ID when calling the play() function.

php
// Create an associative array with unique IDs as keys and music titles as values
$musicTitles = [
    1 => "Song A",
    2 => "Song B",
    3 => "Song C"
];

// Function to play music based on the unique ID
function play($id) {
    global $musicTitles;
    
    if (isset($musicTitles[$id])) {
        echo "Playing: " . $musicTitles[$id];
    } else {
        echo "Music not found";
    }
}

// Call the play function with a specific ID
play(2); // Output: Playing: Song B