How do I count comma-separated values in PHP?

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

    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;
    

提交回复
热议问题