skip to Main Content

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


  1. 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
    

    Or you can build your array adding or not the conditional element. This can be the better solution:

    $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
    
    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search