How do I count comma-separated values in PHP?

前端 未结 5 518
青春惊慌失措
青春惊慌失措 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:37

    Should be

    $result = count(explode(',',$schools));
    
    0 讨论(0)
  • 2020-12-11 05:38

    You need to explode $schools into an actual array:

    $schools = $_SESSION['sarray'];
    $schools_array = explode(",", $schools);
    $result = count($schools_array);
    

    if you just need the count, and are 100% sure it's a clean comma separated list, you could also use substr_count() which may be marginally faster and, more importantly, easier on memory with very large sets of data:

    $result = substr_count( $_SESSION['sarray'], ",") +1; 
     // add 1 if list is always a,b,c;
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-11 05:39
    $schools = $_SESSION['sarray'];
    $array = explode(',', $schools); array_walk($array, 'trim');
    $count = count($array);
    

    The array_walk($array, 'trim') will remove any trailing space in elements value. :)

    0 讨论(0)
  • 2020-12-11 05:46

    Actually, its simpler than that:

    $count = substr_count($schools, ',') + 1;
    
    0 讨论(0)
提交回复
热议问题