Recap: Playlist Exercise
Part of the Logic & Flow section of Coddy's PHP journey — lesson 19 of 68.
Challenge
EasyYou 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
1Advanced Functions
Anonymous FunctionsClosures and 'use'Arrow FunctionsCallback FunctionsUsing 'call_user_func'Variable FunctionsPassing by ReferenceRecursive FunctionsRecap: Function Medley4Multi-dimensional Arrays
Creating a 2D ArrayAccessing 2D Array ElementsModifying 2D Array ElementsIterating with Nested Loops2D Associative ArraysRecap: Simple Grid Exercise2Advanced Array Manipulations
Adding with 'array_push'Removing with 'array_pop'Adding with 'array_unshift'Removing with 'array_shift'Merging Indexed ArraysMerging Associative ArraysExtracting with 'array_slice'Values with 'in_array'Keys with 'array_search'Recap: Playlist Exercise3Sorting Arrays
Sort Indexed Arrays AscendingSort Indexed Arrays DescendingSort Assoc Arrays by ValueSort Assoc Arrays by KeyNatural Order SortingCustom Sorting with 'usort'Recap: Leaderboard Sorting