How to use array_slice() Function In PHP

The array_slice() function is a basic method to get the first N elements from an array. It extracts a portion of an array and returns it.

Example: This example shows the checking of if an array is a subset of another array using array_diff() function.

PHP
<?php

$arr = [1, 2, 3, 4, 5, 6];
$N = 3;
$firstNElements = array_slice($arr, 0, $N);
print_r($firstNElements);

?>

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

How to Get first N number of Elements From an Array in PHP?

Given an array, the task is to get the first N number of elements from the array in PHP. There are various approaches to achieve this task. In this article, we will explore all approaches with detailed explanations.

These are the following approaches:

Table of Content

  • Using array_slice() Function
  • Using for Loop
  • Using foreach Loop
  • Using array_splice() Function

Similar Reads

Using array_slice() Function

The array_slice() function is a basic method to get the first N elements from an array. It extracts a portion of an array and returns it....

Using for Loop

Using a for loop provides a more manual approach to extract the first N elements from an array....

Using foreach Loop

The foreach loop offers another way to achieve this, especially when you want to make the code more readable....

Using array_splice() Function

The array_splice() function can also be used to remove elements from an array and return them. This method modifies the original array....