Recap - Managing a Simple List
Part of the Fundamentals section of Coddy's PHP journey — lesson 40 of 71.
Challenge
EasyBuild 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:
- Start with an empty array called
$shoppingList - Add
item1,item2, anditem3to the array (in that order) - Print the count of items in the array
- Print the first item in the array
- Update the element at
updateIndexwithnewItem - Add
extraItemto the end of the array - Print the new count of items
- Print the last item in the array (use
count()to find the last index) - Print the item at
updateIndexto 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
ButterIf the inputs are Apple, Banana, Orange, 0, Grape, and Mango, the output should be:
3
Apple
4
Mango
GrapeTry 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
4Comparison & Logical Operators
Comparison OperatorsEquality & IdentityLogical Operators Part 1Logical Operators Part 2Recap - Simple Logic2Variables and Data Types
NumbersStrings and QuotesBooleansNaming ConventionsRecap - Variable InitEmpty VariablesString ConcatenationGetting User InputCast to Different Types5Conditional Logic
If StatementIf - ElseThe Ternary OperatorNull Coalescing OperatorSwitch StatementRecap - Making Decisions3Basic Operators
Arithmetic OperatorsModulo OperatorExponentiation OperatorCombined AssignmentIncrement/DecrementOperator PrecedenceRecap - Simple CalculationsString Operators6Arrays Part 1 - Indexed
Introduction to ArraysCreating Indexed ArraysAccessing Elements by IndexModifying Elements by IndexArray Size with CountAdding Elements to an ArrayRecap - Managing a Simple List