Skip to Content
Course content

91: array_slice and array_splice

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I've seen this happen more times than I can count: a developer wants to remove a few items from the middle of an array, they call array_slice(), and then they spend an hour scratching their head wondering why the original array remains completely untouched. It's a classic "pass-by-value" misunderstanding.

The vanishing act that didn't vanish

$inventory = ['Sword', 'Shield', 'Potion', 'Map', 'Key'];

// The goal: Remove the 'Potion' and 'Map' (indices 2 and 3)
array_slice($inventory, 2, 2);

print_r($inventory);
/* 
Output:
Array (
    [0] => Sword
    [1] => Shield
    [2] => Potion
    [3] => Map
    [4] => Key
)
*/

Looking at the code above, it seems logical. You told PHP to start at index 2 and take 2 elements. But if you check the output, the $inventory array hasn't changed. The mistake here is assuming array_slice modifies the source. It doesn't. It's a "read-only" operation that returns a new array containing the slice you requested. It's like taking a photo of a piece of a cake—you have the image of the slice, but the actual cake is still sitting on the table, whole.

Cutting the cake with array_splice

If you actually want to rip elements out of the original array—or replace them with something else—you need array_splice. Think of this as the "surgical" version. It modifies the array in place.

$inventory = ['Sword', 'Shield', 'Potion', 'Map', 'Key'];

// We do the same thing, but with splice
array_splice($inventory, 2, 2);

print_r($inventory);
/* 
Output:
Array (
    [0] => Sword
    [1] => Shield
    [2] => Key
)
*/

Now the 'Potion' and 'Map' are gone. The $inventory array has been mutated. One thing to keep in mind: array_splice actually returns the elements that were removed. So, if you wanted to move those items to a "dropped items" array, you could do $dropped = array_splice($inventory, 2, 2);.

When to actually use array_slice

You might be wondering why array_slice even exists if it doesn't change the array. Well, most of the time, you don't want to destroy your original data. Imagine you're building a pagination system. You have 100 products, and you want to show only products 11 through 20 on page 2. You wouldn't want to delete the other 90 products from your memory just to show one page to the user.

$all_products = ['P1', 'P2', 'P3', ..., 'P100'];
$page_size = 10;
$offset = 10; // Starting at the 11th item

$current_page_items = array_slice($all_products, $offset, $page_size);

In this case, array_slice is perfect because it gives you a window into your data without ruining the original list.

The trick to inserting elements mid-array

Here is a pro tip: array_splice isn't just for removing things. You can use it to inject new elements into the middle of an array. You do this by passing a fourth argument—the replacement array.

$players = ['Alice', 'Bob', 'Charlie'];

// Insert 'Dave' and 'Eve' starting at index 1, removing 0 elements
array_splice($players, 1, 0, ['Dave', 'Eve']);

print_r($players);
/* 
Output:
Array (
    [0] => Alice
    [1] => Dave
    [2] => Eve
    [3] => Bob
    [4] => Charlie
)
*/

By setting the length (the second argument) to 0, you're telling PHP: "Don't delete anything; just push everything from this point forward to the right and jam these new items in here."




📋 Practical Task

Exercise: Building a Dynamic Leaderboard Truncator

You are building a gaming leaderboard. You have an array of players and their scores, but the UI only has room for a "Top 3" display and a "Last Place" display. Additionally, if a player is caught cheating, you need to remove them from the middle of the list without shifting the remaining players' indices manually.

Requirements:

  • Create an array called $leaderboard with at least 6 player names.
  • Use array_slice to create a new array called $top_three containing only the first three players.
  • Use array_slice to create a new array called $last_place containing only the very last player in the list (Hint: look into using a negative offset).
  • Use array_splice to remove the 4th player (index 3) from the $leaderboard array because they were disqualified.
  • Use array_splice to insert a new player, 'Guest_User', at the second position (index 1) of the $leaderboard array.
  • Print all three arrays to verify the results.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.