簡體   English   中英

獲取數組中的第一個和最后一個元素

[英]get first and last element in array

嘿,我有這個數組:

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

我的問題:

如何從這個數組中獲取第一個和最后一個元素,所以我將:

$firstEle = "24.0";

$lastEle = "24.6";

誰知道如何從陣列中獲取這些元素?

我已經嘗試過了:

$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”)元素。 問候

reset()end()這樣做的。

從手冊:

reset() :返回第一個數組元素的值,如果數組為空,則返回FALSE。

end() :返回最后一個元素的值,或返回空數組的FALSE。

例:

<?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)

DEMO


注意 :這將重置您的數組指針,這意味着如果您使用current()來獲取當前元素,或者您已經搜索到數組的中間,則reset()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

您可以使用方括號語法訪問數組元素。 因此要首先使用0 ,因為數組是從零開始索引並count($arr) - 1來獲取最后一項。

$firstEle = $arr[0];
$lastEle = $arr[count($arr) - 1];

您可以使用reset()獲取第一個:

$firstEle = reset($arr);

reset()數組的內部指針倒回第一個元素,並返回第一個數組元素的值。

end()得到最后一個:

$lastEle = end($arr);

end()將數組的內部指針前進到最后一個元素,並返回其值。

從PHP 7.3開始, array_key_firstarray_key_last可用

$first = $array[array_key_first($array)];    
$last = $array[array_key_last($array)];

我們也可以使用數組值和數組鍵來實現目標

示例:數組值

<?php
    $array = array(24.0,24.1,24.2,24.3,24.4,24.5,24.6);        
    $array_values = array_values($array);

    // get the first item in the array
    print array_shift($array_values); 

    // get the last item in the array
    print array_pop($array_values);       
?>

示例:數組鍵

 <?php
    $array = array(24.0,24.1,24.2,24.3,24.4,24.5,24.6);        
    $array_keys = array_keys($array);

    // get the first item in the array
    print $array[array_shift($array_keys)]; 

    // get the last item in the array
    print $array[array_pop($array_keys)];       
?>

對於第一個元素: current($arrayname);

最后一個元素: end($arrayname);

current():current()函數返回數組中當前元素的值。 每個數組都有一個指向其“當前”元素的內部指針,該元素被初始化為插入到數組中的第一個元素。

end():end()函數將內部指針移動到並輸出數組中的最后一個元素。 相關方法:current() - 返回數組中當前元素的值

$array = array(24.0,24.1,24.2,24.3,24.4,24.5,24.6);

$first = current($array);
$last = end($array);

echo 'First Element: '.$first.' :: Last Element:'.$last;

輸出結果:

First Element: 24 :: Last Element:24.6

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM