Home  >  Article  >  Backend Development  >  How to get the last element in an array in php

How to get the last element in an array in php

王林
王林Original
2019-12-02 10:35:1615756browse

How to get the last element in an array in php

Method 1: Use PHP built-in function end()

end() The function points the internal pointer to the array the last element and output it.

<?PHP
$array = array(1,2,4,6,8);
echo end($array);
?>

More learning video recommendations: Getting started with php development

Method 2: Use the function array_pop()

array_pop() Function deletes the last element in the array.

<?PHP
$array = array(1,2,4,6,8);
echo array_pop($array);
?>

Method 3: Use the function array_slice()

array_slice() The function returns the selected part of the array.

Note: If the array has string key names, the returned array will retain the key names.

<?PHP
$array = array(1,2,4,6,8);
$k = array_slice($array,-1,1);
print_r($k);  //结果是一维数组
?>

Recommended related articles and tutorials: php tutorial

The above is the detailed content of How to get the last element in an array in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn