ItSolutionStuff.com

How to Get Last 2 Elements of Array in PHP?

By Hardik Savani • May 14, 2024
PHP

Hi Guys,

In this example, you will learn php array get last 2 elements. This article goes in detailed on php array get 2 last element value. I would like to show you how to get 2 last element of array in php. This example will help you php get 2 last key of array example.

we will use array_slice() function to get last 2 elements of array in php. so, let's see the simple code of how to get last 2 values in php array.

Example:

index.php

<?php

$myArray = ["One", "Two", "Three", "Four"];

$lastElems = array_slice($myArray, -2, 2);

var_dump($lastElems);

?>

Output:

array(2) {

[0]=> string(5) "Three"

[1]=> string(4) "Four"

}

I hope it can help you...

Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

How to Get Last Element of Array in PHP?

Read Now →

How to Use ChatGPT API in PHP?

Read Now →

How to Get First Element of Array in PHP?

Read Now →

How to Remove Last Character from String in PHP?

Read Now →

PHP Crop Image Before Upload using Croppie JS Example

Read Now →

How to Remove Duplicate Values from Array in PHP?

Read Now →

How to Get Folder Path from File Path in PHP?

Read Now →

How to Get Filename from Path in PHP?

Read Now →

How to Convert Array Values to Lowercase in PHP?

Read Now →

How to Add Prefix in Each Key of PHP Array?

Read Now →

How to Get Minimum Key Value of Array in PHP?

Read Now →

How to Count Number of Files in a Directory in PHP?

Read Now →

How to Find Day Name from Specific Date in PHP?

Read Now →

How to Remove Null Values from Array in PHP?

Read Now →