Extracting with 'array_slice'
Part of the Logic & Flow section of Coddy's PHP journey — lesson 16 of 68.
The array_slice() function allows you to extract a portion of an array without modifying the original array. Unlike functions like array_pop() or array_shift() that change the source array, array_slice() creates a new array containing only the elements you specify.
The function takes two main parameters: the offset (starting position) and the length (how many elements to extract):
<?php
$scores = [95, 87, 92, 78, 85, 90, 88];
$topThree = array_slice($scores, 0, 3);
print_r($topThree); // Outputs: Array ( [0] => 95 [1] => 87 [2] => 92 )
print_r($scores); // Original array unchanged
?>The offset parameter tells PHP where to start extracting (0 means the first element), while the length parameter specifies how many elements to take. You can also use negative values for the offset to start counting from the end of the array.
This function is particularly useful when you need to work with a subset of data, such as displaying only the first few items from a large list or extracting a specific range of elements for processing, all while keeping your original data intact.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyYou will receive three inputs: an array of product prices in JSON format, a starting position (offset), and the number of items to extract (length). Read all three inputs, convert the JSON string to an array, use array_slice() to extract the specified portion of the array, and print the extracted slice using print_r().
Input format: Three lines - first line contains a JSON array of numbers (example: [29.99,15.50,42.00,8.75,33.25]), second line contains the offset (starting position), third line contains the length (number of elements to extract)
Expected output: The extracted portion of the array, displayed using print_r()
Cheat sheet
The array_slice() function extracts a portion of an array without modifying the original array.
Syntax: array_slice($array, $offset, $length)
- offset: Starting position (0 = first element)
- length: Number of elements to extract
- Use negative offset to start from the end of the array
<?php
$scores = [95, 87, 92, 78, 85, 90, 88];
$topThree = array_slice($scores, 0, 3);
print_r($topThree); // Array ( [0] => 95 [1] => 87 [2] => 92 )
print_r($scores); // Original array unchanged
?>Try it yourself
<?php
// Read the JSON array of prices
$json_input = fgets(STDIN);
$prices = (array)json_decode($json_input, true);
// Read the offset (starting position)
$offset = intval(fgets(STDIN));
// Read the length (number of elements to extract)
$length = intval(fgets(STDIN));
// TODO: Write your code below to extract the slice and output it
?>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced Functions
Anonymous FunctionsClosures and 'use'Arrow FunctionsCallback FunctionsUsing 'call_user_func'Variable FunctionsPassing by ReferenceRecursive FunctionsRecap: Function Medley4Multi-dimensional Arrays
Creating a 2D ArrayAccessing 2D Array ElementsModifying 2D Array ElementsIterating with Nested Loops2D Associative ArraysRecap: Simple Grid Exercise2Advanced Array Manipulations
Adding with 'array_push'Removing with 'array_pop'Adding with 'array_unshift'Removing with 'array_shift'Merging Indexed ArraysMerging Associative ArraysExtracting with 'array_slice'Values with 'in_array'Keys with 'array_search'Recap: Playlist Exercise3Sorting Arrays
Sort Indexed Arrays AscendingSort Indexed Arrays DescendingSort Assoc Arrays by ValueSort Assoc Arrays by KeyNatural Order SortingCustom Sorting with 'usort'Recap: Leaderboard Sorting