如何访问数组中的最后一个元素?
$array = explode(".", $row[copy]);
$a = $array.length -1;
我想返回这个数组的最后一个元素,但我从中得到的只是-1。
$array = explode(".", $row[copy]);
$a = $array.length -1;
I want to return the last element of this array but all i get from this is -1.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
您还可以使用:
这还将数组内部指针设置为数组的末尾,但它确实可以轻松获取最后一个元素。
You can also use:
This also sets the arrays internal pointer to the end of the array, but it does get you the last element easily.
尝试计数:
Try count:
您还可以使用 array_pop()。 该函数接受一个数组,删除数组的最后一个元素并返回该元素。
这将修改 $array,删除最后一个元素,因此如果您仍然需要该数组进行某些操作,请不要使用它。
You could also use array_pop(). This function takes an array, removes the last element of the array and returns that element.
This will modify the $array, removing the last element, so don't use it if you still need the array for something.
我认为你的第二行应该更像是:
如果你想要数组中的元素,你需要使用方括号。
I think your second line should be more like:
If you want an element from an array you need to use square brackets.
如果你只想决赛后的一切。 如果您需要的只是最后一个元素,您可以尝试
这可以保存生成数组。
If you just want everythng after the final . you could try
This saves generating an array if all you needed was the last element.
实际上,有一个函数可以完全满足您的要求: end()
$res = end(explode('.', $row['copy']) );
Actually, there is a function that does exactly what you want: end()
$res = end( explode('.', $row['copy']) );
由于这是 PHP 标签,我假设您正在使用 PHP,如果是这样,那么您会想要这样做:
但这仅在您的键是数字且从 0 开始时才有效。
如果您想获取最后一个元素一个数组,但没有数字键或者它们不是从 0 开始,那么:
$array =explode(".", $row[copy]);
$revArray = array_reverse($array, true);
$value = $revArray[key($revArray)];
As this is tag as PHP, I'll assume you are using PHP, if so then you'll want to do:
But this will only work if your keys are numeric and starting at 0.
If you want to get the last element of an array, but don't have numeric keys or they don't start at 0, then:
$array = explode(".", $row[copy]);
$revArray = array_reverse($array, true);
$value = $revArray[key($revArray)];
你好,你也可以使用这个:
$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_pop($stack);
print_r($stack);
此后,$stack 将只有 3 个元素
:
(
[0] => 橙子
[1] => 香蕉
[2] => 苹果
)
和 raspberry 将被分配给 $fruit。
hi u can use this also :
$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_pop($stack);
print_r($stack);
After this, $stack will have only 3 elements:
Array
(
[0] => orange
[1] => banana
[2] => apple
)
and raspberry will be assigned to $fruit.
我的 PHP 有点生疏,但这不应该是这样的:
即:“copy”前面不是缺少“$”吗?.length 真的有效吗?
My PHP is a bit rusty, but shouldn't this be:
i.e.: isn't a "$" missing in front of "copy", and does .length actually work?