0
0
PHPprogramming~15 mins

Array slice and splice in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Array slice and splice
📖 Scenario: You are managing a list of fruits in a basket. Sometimes you want to look at a part of the list without changing it, and sometimes you want to remove some fruits and add new ones in their place.
🎯 Goal: Learn how to use PHP array functions array_slice to get a part of an array without changing it, and array_splice to remove and add elements in an array.
📋 What You'll Learn
Create an array called $fruits with exact values: 'apple', 'banana', 'cherry', 'date', 'elderberry'
Create a variable called $start and set it to 1
Use array_slice with $fruits and $start to get a slice called $someFruits
Use array_splice on $fruits starting at $start to remove 2 elements and add 'fig' and 'grape'
Print $someFruits and $fruits arrays using print_r
💡 Why This Matters
🌍 Real World
Managing lists of items where you want to look at parts of the list or change parts of it, like editing a shopping list or playlist.
💼 Career
Understanding how to manipulate arrays is essential for backend development, data processing, and working with collections of data in PHP.
Progress0 / 4 steps
1
Create the initial array of fruits
Create an array called $fruits with these exact values in order: 'apple', 'banana', 'cherry', 'date', 'elderberry'.
PHP
Need a hint?

Use square brackets [] to create the array with the exact fruit names as strings.

2
Set the start index for slicing and splicing
Create a variable called $start and set it to the number 1.
PHP
Need a hint?

Just assign the number 1 to the variable $start.

3
Get a slice of the fruits array
Use array_slice with $fruits and $start to create a new array called $someFruits that contains the part of $fruits starting from index 1.
PHP
Need a hint?

Use array_slice with two arguments: the array and the start index.

4
Remove and add fruits using array_splice and print results
Use array_splice on $fruits starting at $start to remove 2 elements and add 'fig' and 'grape'. Then print $someFruits and $fruits using print_r.
PHP
Need a hint?

Use array_splice with four arguments: the array, start index, number to remove, and an array of new fruits to add. Then use print_r to show both arrays.