How do I count comma-separated values in PHP?

前端 未结 5 615
青春惊慌失措
青春惊慌失措 2020-12-11 05:06

I have a variable holding values separated by a comma (Implode), and I\'m trying to get the total count of the values in that variable. However. count() is just returning 1.

5条回答
  •  执笔经年
    2020-12-11 05:38

    If there is sarray key set in session array, the count will return 1 for an empty string as well.

    $session = array('sarray' => '');
    
    $count = count(explode(',', $session['sarray']));
    
    echo $count;
    
    // => 1
    

    So, if you want to count the number of items in the array, you will have to add an additional check for empty.

    $session = array('sarray' => '');
    
    $count = !empty($session['sarray']) ? count(explode(',', $session['sarray'])) : 0;
    
    echo $count;
    
    // => 0
    

    Now, let's check if this works with items inside sarray.

    $session = array('sarray' => 'foo, bar');
    
    $count = !empty($session['sarray']) ? count(explode(',', $session['sarray'])) : 0;
    
    echo $count;
    
    // => 2
    

    Hope this helps.

提交回复
热议问题