PHP
Summary - Array methods
Build a queue management app using push, pop, merge and slice.
Summary - Array methods
In this group you learned PHP's most common array methods. array_push and array_pop work on the end of an array, while array_shift and array_unshift work on the start. array_merge joins two arrays, array_slice takes a portion.
For lookup, in_array tells you if an item exists and array_search gives its index. Now you will combine them in a queue management and data merging task.
Exercise Queue management
Define a $queue array and start it empty []. Use array_unshift() to add three values to the start in one call, in this order: "Alex", "Maya", "Sam". Then use array_shift() to assign the first element to $next and print it with echo $next . "\n".
Show example solution
First add with array_unshift($queue, "Alex", "Maya", "Sam");. Then take the first with $next = array_shift($queue); and print echo $next . "\n";.
Example solution:
<?php
$queue = [];
// Add to the queue, take the first and print
array_unshift($queue, "Alex", "Maya", "Sam");
$next = array_shift($queue);
echo $next . "\n";
Merge and slice
In the second task we will combine array_merge and array_slice. Merging two lists and then taking a portion of the result is a common need in real projects.
For example, you might want to merge a lesson list with an extra list and take the first three lessons. This is the basis of splitting data lists into sections.
Exercise Merge and take the first two
Define two arrays: $core = ["Math", "Physics"] and $extra = ["Chemistry", "Biology", "History"]. Use array_merge() to combine them into $all. Take the first two elements of $all into $top with array_slice(). Loop with foreach ($top as $lesson) and print each element with echo $lesson . "\n".
Show example solution
First merge with $all = array_merge($core, $extra);. Then take the first two with $top = array_slice($all, 0, 2);. Then loop with foreach ($top as $lesson) { echo $lesson . "\n"; }.
Example solution:
<?php
$core = ["Math", "Physics"];
$extra = ["Chemistry", "Biology", "History"];
// Merge two lists, take the first two and print
$all = array_merge($core, $extra);
$top = array_slice($all, 0, 2);
foreach ($top as $lesson) {
echo $lesson . "\n";
}
Test yourself
-
Which function adds an element to the start?
- array_unshift
- array_push
- array_pop
- array_shift
Show answer
array_unshift — Correct. array_unshift adds to the start.
-
Match each function to its job
- array_merge
- Joins two arrays
- array_slice
- Takes a portion
- in_array
- Checks existence
- array_search
- Returns the index
Next lesson: Key-value pairs