当前位置:  首页>> 技术小册>> PHP合辑3-数组函数

本文将介绍如何使用PHP中的end()函数获取数组中的最后一个元素,并通过示例了解其实现。

end()函数是PHP中的一个内置函数,用于查找给定数组的最后一个元素。end()函数将数组的内部指针指向最后一个元素并返回该元素的值。

语法:

end($array)

参数:该函数接受一个参数$array。它是我们要查找最后一个元素的数组。

返回值:如果数组不为空,则返回数组中最后一个元素的值,否则在失败时返回FALSE。

考虑以下示例。

  1. Input: array('Ram', 'Shita', 'Geeta')
  2. Output: Geeta
  3. Explanation: Here, the input array contain many elements
  4. but output is Geeta i.e, last element of the array
  5. as the end() function returns the last element of an array.

示例1:下面的示例说明了PHP中的end()函数。

  1. <?php
  2. // Input array
  3. $arr = array('Ram', 'Shita', 'Geeta');
  4. // end function print the last
  5. // element of the array.
  6. echo end($arr);
  7. ?>

output:

  1. Geeta

示例2:这个示例说明了如何从数组中检索最后一个元素。

  1. <?php
  2. // Input array
  3. $arr = array('1', '3', 'P');
  4. // end function print the last
  5. // element of the array.
  6. echo end($arr)."\n";
  7. // end() updates the internal pointer
  8. // to point to last element as the
  9. // current() function will now also
  10. // return last element
  11. echo current($arr);
  12. ?>

output:

  1. P
  2. P

该分类下的相关小册推荐: