获取数组中的第一个和最后一个元素 [英] get first and last element in array

查看:84
本文介绍了获取数组中的第一个和最后一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,我有这个数组:

array(1) {
  ["dump"]=>
  string(38) "["24.0",24.1,24.2,24.3,24.4,24.5,24.6]"
}

我的问题:

如何从这个数组中取出第一个和最后一个元素,所以我将有:

how to get the first and the last element out from this array, so i will have:

$firstEle = "24.0";

$lastEle = "24.6";

有人知道如何从数组中获取这些元素吗?

anybody knows how to get those elements from the array?

我已经试过了:

$arr = json_decode($_POST["dump"], true); 

$col0 = $arr[0];
$col1 = $arr[1];
$col2 = $arr[2];
$col3 = $arr[3];
$col4 = $arr[4];
$col5 = $arr[5];
$col6 = $arr[6];

我可以选择 $col0 和 $col6,但数组可能更长,所以需要一种方法来过滤第一个(24.0")和最后一个(24.6")元素.问候

i could chose $col0 and $col6, but the array could be much longer, so need a way to filter the first("24.0") and the last("24.6") element. greetings

推荐答案

reset()end() 正是这样做的.

reset() and end() does exactly this.

来自手册:

reset():返回第一个数组元素的值,如果数组为空,则为 FALSE.

reset(): Returns the value of the first array element, or FALSE if the array is empty.

end():返回空数组的最后一个元素的值或 FALSE.

end(): Returns the value of the last element or FALSE for empty array.

示例:

<?php
    $array = array(24.0,24.1,24.2,24.3,24.4,24.5,24.6);
    
    $first = reset($array);
    $last = end($array);
    
    var_dump($first, $last);
?>

输出:

浮动(24)
浮动(24.6)

float(24)
float(24.6)

演示

注意:如果您使用 current() 获取当前元素或者你已经寻找到数组的中间,reset()end()> 将重置数组指针(到开头和结尾):

NOTE: This will reset your array pointer meaning if you use current() to get the current element or you've seeked into the middle of the array, reset() and end() will reset the array pointer (to the beginning and to the end):

<?php

$array = array(30.0, 24.0, 24.1, 24.2, 24.3, 24.4, 24.5, 24.6, 12.0);
    
// reset — Set the internal pointer of an array to its first element
$first = reset($array);

var_dump($first); // float(30)
var_dump(current($array)); // float(30)

// end — Set the internal pointer of an array to its last element
$last = end($array);
    
var_dump($last); // float(12)
var_dump(current($array)); // float(12) - this is no longer 30 - now it's 12

这篇关于获取数组中的第一个和最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆