Menu
Coddy logo textTech

Recap - Managing a Simple List

Part of the Fundamentals section of Coddy's PHP journey — lesson 40 of 71.

challenge icon

Challenge

Easy

Build a shopping list from scratch by performing a series of operations.

Read the following inputs:

  • A string item1 - the first item to add
  • A string item2 - the second item to add
  • A string item3 - the third item to add
  • An integer updateIndex - the index of the item to update
  • A string newItem - the replacement value for that index
  • A string extraItem - an additional item to add at the end

Perform the following operations in order:

  1. Start with an empty array called $shoppingList
  2. Add item1, item2, and item3 to the array (in that order)
  3. Print the count of items in the array
  4. Print the first item in the array
  5. Update the element at updateIndex with newItem
  6. Add extraItem to the end of the array
  7. Print the new count of items
  8. Print the last item in the array (use count() to find the last index)
  9. Print the item at updateIndex to confirm the update

Print each result on a separate line.

Example:

If the inputs are Milk, Bread, Eggs, 1, Butter, and Cheese, the output should be:

3
Milk
4
Cheese
Butter

If the inputs are Apple, Banana, Orange, 0, Grape, and Mango, the output should be:

3
Apple
4
Mango
Grape

Try it yourself

<?php
// Read inputs
$item1 = trim(fgets(STDIN));
$item2 = trim(fgets(STDIN));
$item3 = trim(fgets(STDIN));
$updateIndex = intval(trim(fgets(STDIN)));
$newItem = trim(fgets(STDIN));
$extraItem = trim(fgets(STDIN));

// TODO: Write your code below
// 1. Start with an empty array called $shoppingList
// 2. Add item1, item2, and item3 to the array
// 3. Print the count of items
// 4. Print the first item
// 5. Update the element at updateIndex with newItem
// 6. Add extraItem to the end
// 7. Print the new count
// 8. Print the last item (use count() to find the last index)
// 9. Print the item at updateIndex

?>

All lessons in Fundamentals