Ok,
我知道所有关于array_pop(),但它删除了最后一个元素。如何获得数组的最后一个元素而不删除它?
这里有一个奖励:
$array = array('a' => 'a', 'b' => 'b', 'c' => 'c');
甚至
$array = array('a', 'b', 'c', 'd');
unset($array[2]);
echo $array[sizeof($array) - 1]; // Output: PHP Notice: Undefined offset: 2 in - on line 4
避免引用传递错误的一种方法(例如。"end(array_values($foo))")是使用call_user_func或call_user_func_array:
// PHP Fatal error: Only variables can be passed by reference
// No output (500 server error)
var_dump(end(array(1, 2, 3)));
// No errors, but modifies the array's internal pointer
// Outputs "int(3)"
var_dump(call_user_func('end', array(1, 2, 3)));
// PHP Strict standards: Only variables should be passed by reference
// Outputs "int(3)"
var_dump(end(array_values(array(1, 2, 3))));
// No errors, doesn't change the array
// Outputs "int(3)"
var_dump(call_user_func('end', array_values(array(1, 2, 3))));
要获取数组的最后一个元素,使用:
$lastElement = array_slice($array, -1)[0];
基准
我迭代了1,000次,分别获取包含100个和50,000个元素的小型和大型数组的最后一个元素。
Method: $array[count($array)-1];
Small array (s): 0.000319957733154
Large array (s): 0.000526905059814
Note: Fastest! count() must access an internal length property.
Note: This method only works if the array is naturally-keyed (0, 1, 2, ...).
Method: array_slice($array, -1)[0];
Small array (s): 0.00145292282104
Large array (s): 0.499367952347
Method: array_pop((array_slice($array, -1, 1)));
Small array (s): 0.00162816047668
Large array (s): 0.513121843338
Method: end($array);
Small array (s): 0.0028350353241
Large array (s): 4.81077480316
Note: Slowest...
我使用的是PHP 5.5.32版本。