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
.
2
Answers
Sure, a
null
valued element is still considered a valid array element!For example:
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:
Or simply iterate to count not null elements.
Or you can build your array adding or not the conditional element. This can be the better solution:
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)
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