unfulvio
unfulvio

Reputation: 836

How to count order number of values in an array?

I have an array with a few values and want to do something like this:

 $arrayvalues = array_reverse(explode(', ', somefunction()));
 foreach ( $arrayvalues as $arrayvalue ) :
           printf('<li class="'.$countvalue.'">'.$arrayvalue.'</li>');  
 endforeach;

I want to have in $countvalue the number of the value in the array

ie... the array will be something like this: ("apple", "orange", "grapefruit")

I want the number to match the order number of these values apple = 1, orange = 2, grapefruit = 3

or actually even if it's just an incremental number according to the values echoed it doesn't matter, I just need to insert a css class represented by an incremembtal number

I tried playing $i... count... but I don't know how to achieve what I want; I'm more a designer than a coder, I looked in the PHP help but couldn't find a clear solution for my case

thank you

Upvotes: 1

Views: 282

Answers (4)

vascowhite
vascowhite

Reputation: 18440

You already have an incremental number based on order. Keep in mind, this only works if your key's are 0-based. If you use an associative array you will need to use a for loop instead (as suggested by nickb).

$arrayvalues = array_reverse(explode(', ', somefunction()));
foreach ( $arrayvalues as $key => $arrayvalue ){
    echo "<li class='$key'>$arrayvalue</li>";
}

Upvotes: 4

Leysam Rosario
Leysam Rosario

Reputation: 369

 $arrayvalues = array_reverse(explode(', ', somefunction()));
 $i=0;
 foreach ( $arrayvalues as $arrayvalue ) :
           ++$i;
           $countvalue = $i;
           printf('<li class="'.$countvalue.'">'.$arrayvalue.'</li>');  
 endforeach;

We (or I) advise you use a normal for loop.

for($i = 0; $i < count($arrayvalues); $i++) {
     printf('<li class="'.($i+1).'">'.$arrayvalue.'</li>');  
}

Upvotes: 0

nickb
nickb

Reputation: 59699

Use a for loop to iterate over your array, like so:

 for( $i = 0, $j = count( $arrayvalues); $i < $j; $i++) :
           printf('<li class="' . ($i + 1) . '">' . $arrayvalues[$i] . '</li>');
 endfor;

If you want the index $i to start at one, you need to add one in the printf statement.

Side note: You don't need printf here if you're not actually generating formatted output.

Upvotes: 0

Polynomial
Polynomial

Reputation: 28316

 $arrayvalues = array_reverse(explode(', ', somefunction()));
 $i = 0;
 foreach ( $arrayvalues as $arrayvalue )
 {
           $i++;
           printf('<li class="'.$i.'">'.$arrayvalue.'</li>');
 }

Upvotes: 1

Related Questions