end
(PHP 4, PHP 5, PHP 7, PHP 8)
end — 将数组的内部指针指向最后一个单元
参数
array
-
这个数组。 该数组是通过引用传递的,因为它会被这个函数修改。 这意味着你必须传入一个真正的变量,而不是函数返回的数组,因为只有真正的变量才能以引用传递。
返回值
返回最后一个元素的值,或者如果是空数组则返回 false
。
更新日志
版本 | 说明 |
---|---|
8.1.0 | 弃用在 object 上调用此函数。 要么首先使用 get_mangled_object_vars() 将 object 转换为 array,要么使用实现 Iterator 的类提供的方法,例如 ArrayIterator。 |
7.4.0 | SPL 类的实例现在被视为没有属性的空对象,而不是调用与此函数同名的 Iterator 方法。 |
示例
示例 #1 end() 例子
<?php
$fruits = array('apple', 'banana', 'cranberry');
echo end($fruits); // cranberry
?>
+添加备注
用户贡献的备注 5 notes
franz at develophp dot org ¶
14 years ago
It's interesting to note that when creating an array with numeric keys in no particular order, end() will still only return the value that was the last one to be created. So, if you have something like this:
<?php
$a = array();
$a[1] = 1;
$a[0] = 0;
echo end($a);
?>
This will print "0".
jasper at jtey dot com ¶
18 years ago
This function returns the value at the end of the array, but you may sometimes be interested in the key at the end of the array, particularly when working with non integer indexed arrays:
<?php
// Returns the key at the end of the array
function endKey($array){
end($array);
return key($array);
}
?>
Usage example:
<?php
$a = array("one" => "apple", "two" => "orange", "three" => "pear");
echo endKey($a); // will output "three"
?>
jorge at REMOVETHIS-2upmedia dot com ¶
12 years ago
If all you want is the last item of the array without affecting the internal array pointer just do the following:
<?php
function endc( $array ) { return end( $array ); }
$items = array( 'one', 'two', 'three' );
$lastItem = endc( $items ); // three
$current = current( $items ); // one
?>
This works because the parameter to the function is being sent as a copy, not as a reference to the original variable.
Anonymous ¶
22 years ago
If you need to get a reference on the first or last element of an array, use these functions because reset() and end() only return you a copy that you cannot dereference directly:
<?php
function first(&$array) {
if (!is_array($array)) return &$array;
if (!count($array)) return null;
reset($array);
return &$array[key($array)];
}
function last(&$array) {
if (!is_array($array)) return &$array;
if (!count($array)) return null;
end($array);
return &$array[key($array)];
}
?>
ivijan dot stefan at gmail dot com ¶
10 years ago
I found that the function end() is the best for finding extensions on file name. This function cleans backslashes and takes the extension of a file.
<?php
private function extension($str){
$str=implode("",explode("\\",$str));
$str=explode(".",$str);
$str=strtolower(end($str));
return $str;
}
// EXAMPLE:
$file='name-Of_soMe.File.txt';
echo extension($file); // txt
?>
Very simple.