Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php count the number of strings after exploded

Here is my code

<?php

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

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


foreach($tags as $i =>$key) {
$i >0;
    echo $i.' '.$key .'</br>';

}

?>

the output is

0 a
1 b
2 c
3 d
4 e
5 f

What i'm try to count the number of strings after i exploded | (it should be 6 for my example) also i need my $i to start from 1 not 0

Any idea please ?

Thank you.

like image 884
user2203703 Avatar asked May 11 '13 23:05

user2203703


3 Answers

<?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)

like image 149
Daryl Gill Avatar answered Oct 27 '22 00:10

Daryl Gill


<?php

$string = 'a|b|c|d|e|f';
$array= explode('|' , $string);
 for($i = 0;$i<count($array);$i++){
  echo $i. $array[$i]."\n";
}

?>
like image 30
Avigit.M Avatar answered Oct 27 '22 00:10

Avigit.M


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

$tags = explode('|' , $string);
$num_tags = count($tags);
like image 33
Karl M.W. Avatar answered Oct 27 '22 00:10

Karl M.W.