gpt4 book ai didi

php - 如果我不指定,数组元素的键是什么

转载 作者:行者123 更新时间:2023-12-02 06:59:36 26 4
gpt4 key购买 nike

我想知道是否所有 PHP 数组的 value 都必须有 key?我不认为他们这样做,所以我的下一个问题是,每个 valuekey 是否自动成为它在数组中的位置(基于 0 的索引),或者否则 value 本身会变成 key 吗?

也许值只是没有键...好奇,因为如果没有键,我无法从 foreach 循环内的数组中删除元素。

最佳答案

I'm wondering if all PHP arrays have to have keys for their values?

是的。来自documentation :

Arrays

An array in PHP is actually an ordered map. A map is a type that associates values to keys.

因此,数组的所有元素都必须有一个键。

does the key for each value automatically become it's position in the array (0-based indexing)

几乎正确。如果一个元素没有指定键,则该键为1+前一个元素的键,第一个元素的键为0。

I can't delete an element from an array inside a foreach loop if it doesn't have a key.

实际上有foreach除值外还公开键的语法。来自documentation :

The foreach construct provides an easy way to iterate over arrays. foreach works only on arrays and objects, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable. There are two syntaxes:

foreach (array_expression as $value)
statement
foreach (array_expression as $key => $value)
statement

使用后一种foreach语法删除数组元素的例子如下:

// Remove elements from the array that are less than 10
foreach ($array as $key => $value) {
if ($value < 10) {
unset($array[$key]);
}
}

关于php - 如果我不指定,数组元素的键是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23554590/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com