Web4College

Methods to get the last element of an array in PHP

There are many methods we can use to get the last element of an array. There are also some built-in functions in php to find the last element of an array. We'll discuss both the built-in functions as well as our custom methods to find the end element of an array.

1. index method

If we have the size of an array, we can get the required element. And we'll use (size-1) as index to find the end element of an array.

Example

$arr = ["HTML", "CSS", "JavaScript", "PHP", "SQL", "JQuery"];

echo $arr[5]; // JQuery

Remember that the index of array starts from 0.

2. end() method

There is a built-in function called end() function. It points the pointer at the end of array and returns the last element of array.

Example

$arr = ["HTML", "CSS", "JavaScript", "PHP", "SQL", "JQuery"];

echo end($arr); // JQuery

It is returning last element of array i.e. JQuery.

The pointer points to the last element. You can check the current position of pointer after applying the end() function with current() function.

Example

$arr = ["HTML", "CSS", "JavaScript", "PHP", "SQL", "JQuery"];

echo end($arr); // JQuery

echo current($arr) // JQuery

You can see the current() function returns the last element of array i.e. JQuery.

3. count() method

In this method, count function counts the array elements and returns the size of array. Then, we use this size to get the last element of an array.

Example

$arr = ["HTML", "CSS", "JavaScript", "PHP", "SQL", "JQuery"];

echo $arr[count($arr)]; // JQuery

4. array_pop() method

This method pops out the last element of an array. Pop means the last element is also deleted from the array.

Example


$arr = ["HTML", "CSS", "JavaScript", "PHP", "SQL", "JQuery"];

echo array_pop($arr); // 6

$lastElement = array_pop($arr);

echo $lastElement; // JQuery

echo count($arr); // 5

See the example give above. Check the size of array before and after applying the array_pop() function.


PHP

How to split string into array in php

PHP implode() function to concatenate the associative array values with multiple delimiters