为什么仍然返回 3 的计数?
$arr =
[
[
'slug' => 'products-services-pricing',
'text' => 'Products/Services and Pricing',
],
[
'slug' => 'promotions-plan',
'text' => 'Promotions Plan',
],
(1 == 2) ?
[
'slug' => 'distribution-plan',
'text' => 'Distribution Plan',
] : null,
];
echo "Count = ".count($arr)."\n";
print_r($arr);
我的
foreach
变得一团糟。 PHP 8.0foreach
因为我正在使用 count
。
当然,
null
值元素仍然被视为有效的数组元素!
例如:
<?php
$arr = [null, null, null];
echo 'Count: ' . count($arr); //Will print 3
在您的代码中,第三个元素的值是
null
,这没有问题,没有什么神秘的。您不是删除该元素,而是为其分配一个值:null
。
这里你有一个想法:迭代数组并删除值为 null 的元素:
$aux = [];
foreach ($arr as $item) {
if (!is_null($item)) {
$aux[] = $item;
}
}
$arr = $aux; //Now $arr has no null elements
或者简单地迭代计算非空元素。
$c = 0;
foreach ($arr as $item) {
if (!is_null($item)) {
$c++;
}
}
echo 'Count: ' . $c; //Count without null elements
或者您可以构建数组,添加或不添加条件元素。这可能是更好的解决方案:
$arr =
[
[
'slug' => 'products-services-pricing',
'text' => 'Products/Services and Pricing',
],
[
'slug' => 'promotions-plan',
'text' => 'Promotions Plan',
],
];
if (1 == 2) {
$arr[] = [
'slug' => 'distribution-plan',
'text' => 'Distribution Plan',
];
}
echo 'Count: ' . count($arr); //Will print 2
如果您更改三元返回的值并使用扩展运算符,您将能够实现您想要的效果,而无需任何后续过滤或胡闹。
代码:(演示)
...(1 == 2)
? [['slug' => 'distribution-plan', 'text' => 'Distribution Plan']]
: [],
通过向真实分支值添加深度级别,扩展运算符会将单行推入数组中。
通过将
null
更改为空数组,扩展运算符不会将任何内容推入数组中。
有点,有点,相关:
应该可以像 JavaScript 一样传播强制转换值。
console.log([1, 2, ...([].concat(null ?? []))]);
console.log([1, 2, ...([].concat(3 ?? []))]);
[ 1, 2 ]
[ 1, 2, 3 ]
$a = null;
$b = '123';
$c = 456;
$d = [789];
$r = [
// Spread `null` won't appear in the array.
...(null) ?? [],
...((array) null) ?? [],
...($a) ?? [],
...((array) $a) ?? [],
// Cast is required to wrap into arrays to spread.
// ...($b) ?? [], // Fatal error: Uncaught Error: Only arrays and Traversables can be unpacked...
...((array) $b) ?? [],
...((array) $c) ?? [],
...((array) $d) ?? []
];
var_dump(null, (array) null, $r);
NULL
array(0) {}
array(3) {
[0]=> string(3) "123"
[1]=> int(456)
[2]=> int(789)
}