>本教程提供了對PHP陣列的基本理解。 我們將介紹數組創建,關聯和多維數組,並用實際的示例說明它們的用法。
什麼是PHP數組?
在PHP中,陣列是一種多功能數據結構,可在單個變量中存儲多個值。這些值被組織為鍵值對。 數組是存儲相關數據列表的理想選擇,通常具有相同數據類型的元素。
例如,要存儲一個水果列表,而不是使用單獨的變量,您可以使用一個數組:
陣列解開包裝
$fruits = array('Apple', 'Orange', 'Watermelon', 'Mango');
PHP使用差異操作員(array()
)提供陣列拆開的陣列。 最初,這僅適用於數字索引數組。 但是,php 8.1用字符串鍵擴展對數組的支持。
$fruits = ['Apple', 'Orange', 'Watermelon', 'Mango'];
>帶有字符串鍵的示例(請注意現有密鑰是如何覆蓋的):
>
...
請記住,將字符串密鑰解開覆蓋現有鍵,而數字鍵被重新索引。
$plantEaters = ["Horse", "Goat", "Rabbit"]; $meatEaters = ["Lion", "Tiger", "Crocodile"]; $animals = ["Dog", ...$plantEaters, ...$meatEaters, "Cat"]; print_r($animals); /* Array ( [0] => Dog [1] => Horse [2] => Goat [3] => Rabbit [4] => Lion [5] => Tiger [6] => Crocodile [7] => Cat ) */
$defaultColors = ["body" => "red", "heading" => "blue", "sidebar" => "yellow"]; $userColors = ["body" => "white", "paragraph" => "black"]; $themeColors = [...$defaultColors, ...$userColors]; print_r($themeColors); /* Array ( [body] => white [heading] => blue [sidebar] => yellow [paragraph] => black ) */
函數對於刪除和/或更換數組的部分是無價的。它需要四個參數:數組,起始偏移量,要刪除的元素數和可選的替換數組。
array_splice()
結論
>本簡介涵蓋了PHP陣列的必需品。您已經學會瞭如何創建和操縱數組,包括使用陣列解開包裝和array_splice()
>函數。 該基礎將使您能夠有效地利用PHP項目中的數組。
$items = ["Charger", "Keyboard", "Smartphone", "Baseball", "Bat", "Mouse"]; $replacements = ["Pen", "Headphones"]; array_splice($items, 3, 2, $replacements); print_r($items); /* Array ( [0] => Charger [1] => Keyboard [2] => Smartphone [3] => Pen [4] => Headphones [5] => Mouse ) */
該教程通過其他信息進行了增強。
以上是了解PHP中的陣列的詳細內容。更多資訊請關注PHP中文網其他相關文章!