生成器中的密钥铸造
Keys casting in generators
中数组键的引用开始这个问题
If no key is specified, the maximum of the existing integer indices is taken, and the new key will be that maximum value plus 1 (but at least 0). If no integer indices exist yet, the key will be 0 (zero).
所以让我们在下面的代码中尝试一下:
print_r(['4'=> 1, 2, 3]); // output: Array([4] => 1 [5] => 2 [6] => 3)
*注意数组中第一个key是字符串会被PHP强制转换为整数类型[4]
现在让我们在生成器函数中尝试这个,一个一个地生成数组键,看看会发生什么
function foo() {
yield '4' => 1;
yield 2;
yield 3;
}
print_r(iterator_to_array(foo()));// output: Array([4] => 1 [0] => 2 [1] => 3)
我知道生成器的行为不像数组,但让我们看看当第一个键实际上是整数时会发生什么:
function foo() {
yield 4 => 1; // Note 4 here is an integer
yield 2;
yield 3;
}
print_r(iterator_to_array(foo())); // output: Array([4] => 1 [5] => 2 [6] => 3)
输出符合预期。
那么为什么只有当 PHP 在生成器中转换密钥时才会发生这种情况?这是正常行为吗?
如果数组中的键是数字字符串,PHP将其转换为整数类型。在生成器中,数字字符串键不会转换为整数。如果要保留密钥类型,则一定不要使用iterator_to_array函数。
function foo() {
yield '4' => 1;
yield 2;
yield 3;
}
foreach(foo() as $key => $value){
var_dump($key);
}
输出:
string(1) "4"
int(0)
int(1)
If no key is specified, the maximum of the existing integer indices is taken, and the new key will be that maximum value plus 1 (but at least 0). If no integer indices exist yet, the key will be 0 (zero).
所以让我们在下面的代码中尝试一下:
print_r(['4'=> 1, 2, 3]); // output: Array([4] => 1 [5] => 2 [6] => 3)
*注意数组中第一个key是字符串会被PHP强制转换为整数类型[4]
现在让我们在生成器函数中尝试这个,一个一个地生成数组键,看看会发生什么
function foo() {
yield '4' => 1;
yield 2;
yield 3;
}
print_r(iterator_to_array(foo()));// output: Array([4] => 1 [0] => 2 [1] => 3)
我知道生成器的行为不像数组,但让我们看看当第一个键实际上是整数时会发生什么:
function foo() {
yield 4 => 1; // Note 4 here is an integer
yield 2;
yield 3;
}
print_r(iterator_to_array(foo())); // output: Array([4] => 1 [5] => 2 [6] => 3)
输出符合预期。
那么为什么只有当 PHP 在生成器中转换密钥时才会发生这种情况?这是正常行为吗?
如果数组中的键是数字字符串,PHP将其转换为整数类型。在生成器中,数字字符串键不会转换为整数。如果要保留密钥类型,则一定不要使用iterator_to_array函数。
function foo() {
yield '4' => 1;
yield 2;
yield 3;
}
foreach(foo() as $key => $value){
var_dump($key);
}
输出:
string(1) "4"
int(0)
int(1)