php count the number of strings after exploded
Asked Answered
Z

5

11

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.

Zackaryzacks answered 11/5, 2013 at 23:37 Comment(1)
What do you normally do to count() items in an array?Tangleberry
L
23
<?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)

Limitary answered 11/5, 2013 at 23:41 Comment(3)
If you create a simple array: $Var = array("First","second"); then issue print_r($Var); you will notice the keys will always start at 0. This is the primary index for every created array. hence you getting the output you have got. You would need to re-index your array before your loop but after creating the array to get keys as: array(1,2,3,4,5,6);Limitary
Re-index the array?? Why not simply add 1?Tangleberry
@PeeHaa埽 I was thinking of the array displaying aspects aswellLimitary
Q
9

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

$tags = explode('|' , $string);
$num_tags = count($tags);
Quaff answered 11/5, 2013 at 23:41 Comment(0)
F
3
<?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++;
}

?>
Flaccid answered 1/12, 2016 at 6:52 Comment(0)
H
1
<?php

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

?>
Herzl answered 5/2, 2020 at 6:29 Comment(1)
While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value.Outrun
F
0

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

Feliciafeliciano answered 11/5, 2013 at 23:42 Comment(1)
"programmers always count from 0" actually it depends on the languageTangleberry

© 2022 - 2024 — McMap. All rights reserved.