php count the number of strings after exploded

女生的网名这么多〃 提交于 2019-11-30 18:53:26
<?php

$string = 'a|b|c|d|e|f';

$tags = explode('|' , $string);


foreach($tags as $i =>$key) {

    echo $i.' '.$key .'</br>';

}

?>

Try using:

echo count($tags); // Output of 6

Arrays start with a key of 0, not one. So when using anything else apart from count, you will constantly get 1 less than your expected (unless you modify the array prior to counting)

If you just need the total number, you could do this:

$tags = explode('|' , $string);
$num_tags = count($tags);
<?php

$string = 'a|b|c|d|e|f';

$tags = explode('|' , $string);

$count =count($tags);
  echo 'Count is: '.$count .'</br>';
$i = 1 ;
foreach($tags as $key) {

    echo $i.' '.$key .'</br>';
$i++;
}

?>

programmers always count from 0, it's good practice, but if you really need to do this simply declare the $i variable as 1 before the fooreach loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!