如何在 PHP 中獲取陣列的第一個元素

Minahil Noor 2023年1月30日 PHP PHP Array
  1. 使用元素索引獲取 PHP 中陣列的第一個元素
  2. 使用 reset() 函式獲取 PHP 中陣列的第一個元素
  3. 使用 current() 函式獲取 PHP 中陣列的第一個元素
如何在 PHP 中獲取陣列的第一個元素

在本文中,我們將介紹在 PHP 中獲取陣列的第一個元素的方法。

  • 使用元素索引
  • 使用 reset() 函式
  • 使用 current() 函式

使用元素索引獲取 PHP 中陣列的第一個元素

我們知道陣列中第一個元素的索引為 0,因此,你可以通過對其進行訪問來直接獲取第一個元素指數。通過索引獲取元素的正確語法如下

$arrayName[0];

為了獲得第一個元素,將第一個元素的索引 0 與陣列名稱一起放在方括號中。

<?php
$flowers = array("Rose","Lili","Jasmine","Hibiscus","Tulip","Sun Flower","Daffodil","Daisy");
$firstElement = $flowers[0];
echo "The first element of the array is $firstElement."
?>

輸出:

The first element of the array is Rose.

使用 reset() 函式獲取 PHP 中陣列的第一個元素

內建函式 reset() 將陣列的指標設定為其起始值,即陣列的第一個元素。

reset($arrayName);

它只有一個引數。如果陣列不為空,則返回第一個元素的值。如果陣列為空,則返回 false

<?php
$flowers = array("Rose","Lili","Jasmine","Hibiscus","Tulip","Sun Flower","Daffodil","Daisy");
$firstElement = reset($flowers);
echo "The first element of the array is $firstElement."
?>

輸出:

The first element of the array is Rose.

使用 current() 函式獲取 PHP 中陣列的第一個元素

current() 函式是另一個內建函式,用於獲取指標當前指向的陣列中的值。如果陣列中沒有內部指標,則可用於獲取陣列的第一個元素。指標預設情況下指向第一個元素。使用此函式的正確語法如下

current($arrayName);

它只接受一個引數 $arrayName。引數 $arrayName 是一個我們想要獲取第一個元素的陣列。

<?php
$flowers = array("Rose","Lili","Jasmine","Hibiscus","Tulip","Sun Flower","Daffodil","Daisy");
$firstElement = current($flowers);
echo "The first element of the array is $firstElement."
?>

輸出:

The first element of the array is Rose.
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe

相關文章 - PHP Array