Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • PHP Tutorial
  • PHP Exercises
  • PHP Array
  • PHP String
  • PHP Calendar
  • PHP Filesystem
  • PHP Math
  • PHP Programs
  • PHP Array Programs
  • PHP String Programs
  • PHP Interview Questions
  • PHP GMP
  • PHP IntlChar
  • PHP Image Processing
  • PHP DsSet
  • PHP DsMap
  • PHP Formatter
  • Web Technology
Open In App
Next Article:
How to Paginate an Array in JavaScript?
Next article icon

How to Slice an Array in PHP?

Last Updated : 04 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In PHP, slicing an array means taking a subset of the array and extracting it according to designated indices. When you need to extract a subset of elements from an array without changing the original array, this operation comes in handy. PHP comes with a built-in function called array_slice() to help you do this task quickly.

These are the following approaches:

Table of Content

  • Using array_slice() Function
  • Using a Custom Function

Using array_slice() Function

The array_slice() function is the standard way to slice an array in PHP. This function allows you to specify the starting index, the length of the slice, and whether to preserve the array keys.

Syntax:

array_slice(array $array, int $offset, ?int $length = null, bool $preserve_keys = false): array

Example: This example shows the creation of a custom function to slice an array.

PHP
<?php    $input = [1, 2, 3, 4, 5, 6, 7]; $slice = array_slice($input, 2, 3); print_r($slice);  ?> 

Output
Array (     [0] => 3     [1] => 4     [2] => 5 ) 

Using a Custom Function

Even though array_slice() usually works well, you can write a custom function to slice an array by hand. This could be helpful when adding more logic to the slicing process or in learning scenarios.

Syntax:

function custom_slice(array $array, int $offset, int $length): array {
$sliced_array = [];
for ($i = $offset; $i < $offset + $length; $i++) {
if (isset($array[$i])) {
$sliced_array[] = $array[$i];
}
}
return $sliced_array;
}

Example: This example shows the creation of a custom function to slice an array.

PHP
<?php // Define the custom_slice() function function custom_slice(array $array, int $offset, int $length): array {     $sliced_array = [];     for ($i = $offset; $i < $offset + $length; $i++) {         if (isset($array[$i])) {             $sliced_array[] = $array[$i];         }     }     return $sliced_array; }  // Now call the custom_slice() function $input = ['apple', 'banana', 'cherry', 'date', 'elderberry']; $slice = custom_slice($input, 1, 3); print_r($slice); ?> 

Output
Array (     [0] => banana     [1] => cherry     [2] => date ) 

Next Article
How to Paginate an Array in JavaScript?

H

heysaiyad
Improve
Article Tags :
  • Web Technologies
  • PHP

Similar Reads

  • How to reset Array in PHP ?
    You can reset array values or clear the values very easily in PHP. There are two methods to reset the array which are discussed further in this article. Methods: unset() Functionarray_diff() Function Method 1: unset() function: The unset() function is used to unset a specified variable or entire arr
    2 min read
  • How to Paginate an Array in JavaScript?
    Pagination is a common requirement in web applications especially when dealing with large datasets. It involves dividing a dataset into smaller manageable chunks or pages. In JavaScript, we can paginate an array by splitting it into smaller arrays each representing a page of the data. Below are the
    2 min read
  • PHP array_slice() Function
    The array_slice() is an inbuilt function of PHP and is used to fetch a part of an array by slicing through it, according to the users choice.Syntax: array_slice($array, $start_point, $slicing_range, preserve) Parameters: This function can take four parameters and are described below: $array (mandato
    3 min read
  • PHP array_splice() Function
    This inbuilt function of PHP is an advanced and extended version of array_slice() function, where we not only can remove elements from an array but can also add other elements to the array. The function generally replaces the existing element with elements from other arrays and returns an array of r
    2 min read
  • How to display array structure and values in PHP ?
    In this article, we will discuss how to display the array structure and values in PHP. To display the array structure and its values, we can use var_dump() and print_r() functions. It includes Array sizeArray valuesArray value with IndexEach value data type We will display the array structure using
    2 min read
  • How to Check an Array is Sorted or Not in PHP?
    Given an array, the task is to check whether the given array is sorted or not. Arrays are often used to store and manipulate data. One common task is to check if an array is sorted in ascending or descending order. This article will explore different approaches to determine whether an array is sorte
    3 min read
  • How to convert an array to CSV file in PHP ?
    To convert an array into a CSV file we can use fputcsv() function. The fputcsv() function is used to format a line as CSV (comma separated values) file and writes it to an open file. The file which has to be read and the fields are sent as parameters to the fputcsv() function and it returns the leng
    2 min read
  • PHP Change strings in an array to uppercase
    Changing strings in an array to uppercase means converting all the string elements within the array to their uppercase equivalents. This transformation modifies the array so that every string, regardless of its original case, becomes fully capitalized. Examples: Input : arr[] = ("geeks", "For", "GEE
    3 min read
  • How to Truncate an Array in JavaScript?
    Here are the different methods to truncate an array in JavaScript 1. Using length PropertyIn Array.length property, you can alter the length of the array. It helps you to decide the length up to which you want the array elements to appear in the output. [GFGTABS] JavaScript const n = [1, 2, 3, 4, 5,
    4 min read
  • How to read each character of a string in PHP ?
    A string is a sequence of characters. It may contain integers or even special symbols. Every character in a string is stored at a unique position represented by a unique index value. Here are some approaches to read each character of a string in PHP Table of Content Using str_split() method - The st
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences