php count the number of strings after exploded

前端 未结 5 971

Here is my code

$key) {
$i >0;
    echo $i.\' \'.$key .         


        
相关标签:
5条回答
  • 2021-01-04 18:42
    <?php
    
    $string = 'a|b|c|d|e|f';
    $array= explode('|' , $string);
     for($i = 0;$i<count($array);$i++){
      echo $i. $array[$i]."\n";
    }
    
    ?>
    
    0 讨论(0)
  • 2021-01-04 18:46

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

    $tags = explode('|' , $string);
    $num_tags = count($tags);
    
    0 讨论(0)
  • 2021-01-04 18:50
    <?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++;
    }
    
    ?>
    
    0 讨论(0)
  • 2021-01-04 18:53

    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

    0 讨论(0)
  • 2021-01-04 19:07
    <?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)

    0 讨论(0)
提交回复
热议问题