Menu
Coddy logo textTech

Recap: Playlist Exercise

Part of the Logic & Flow section of Coddy's PHP journey — lesson 19 of 68.

challenge icon

Challenge

Easy

You will receive four inputs: an initial playlist array in JSON format, a song to add to the end, a song to add to the beginning, and a song name to search for. Read all four inputs, convert the JSON string to an array, add the second song to the end using array_push(), add the third song to the beginning using array_unshift(), then use array_search() to find the position of the fourth song in the modified playlist. Print the position if found, or print "Song not found" if it doesn't exist in the playlist.

Input format: Four lines - first line contains a JSON array of songs (example: ["Song A","Song B","Song C"]), second line contains a song name to add at the end, third line contains a song name to add at the beginning, fourth line contains a song name to search for

Expected output: Either the numeric index position of the searched song (starting from 0) in the modified playlist, or the text "Song not found" if the song doesn't exist

Try it yourself

<?php
// Read all four inputs
$playlistJson = trim(fgets(STDIN));
$songToAddEnd = trim(fgets(STDIN));
$songToAddBeginning = trim(fgets(STDIN));
$songToSearch = trim(fgets(STDIN));

// Convert JSON string to array
$playlist = (array)json_decode($playlistJson, true);

// TODO: Write your code below
// 1. Add $songToAddEnd to the end of the playlist using array_push()
// 2. Add $songToAddBeginning to the beginning of the playlist using array_unshift()
// 3. Search for $songToSearch in the modified playlist using array_search()
// 4. Store the result and print either the position or "Song not found"

// Output the result
echo $result;
?>

All lessons in Logic & Flow