Why is this still returning a count of 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);
My foreach
is getting messed up. PHP 8.0
I cannot do condition check in foreach
because I am using count
.
CodePudding user response:
Sure, a null
valued element is still considered a valid array element!
For example:
<?php
$arr = [null, null, null];
echo 'Count: ' . count($arr); //Will print 3
In your code, the value of the third element is null
, there is no problem with that, no mistery. You are not removing the element, but assigning it a value: null
.
Here you got an idea: iterate over the array and remove elements valued null:
$aux = [];
foreach ($arr as $item) {
if (!is_null($item)) {
$aux[] = $item;
}
}
$arr = $aux; //Now $arr has no null elements
Or simply iterate to count not null elements.
$c = 0;
foreach ($arr as $item) {
if (!is_null($item)) {
$c ;
}
}
echo 'Count: ' . $c; //Count without null elements
CodePudding user response:
If you change the values returned by your ternary and use the spread operator, you'll be able to achieve what you want without any subsequent filtering or fooling around.
Code: (Demo)
...(1 == 2)
? [['slug' => 'distribution-plan', 'text' => 'Distribution Plan']]
: [],
By adding a level of depth to the true branch value, the spread operator will push the single row into the array.
By changing null
to an empty array, the spread operator will push nothing into the array.
Kind of, sort of, related:
PHP is there a way to add elements calling a function from inside of array