Dan
Dan

Reputation: 12096

Get the position of an array item in php

Say I have an array similar to the following and I'm looping through it as such:

$sidebar = array("Best of the Month" => $featuredBestMonth, 
                 "Featured Content"  => $featuredContent);

<? while($item = current($sidebar)):?>
    <? if($item):?>

         <h3><?=key($sidebar);?></h3>

         <? foreach($item as $single):?>
            <p><?=$single['title'];?></p>
        <? endforeach;?>

    <? endif;?>
    <? next($sidebar);?>
<? endwhile;?>

How can I count the current array number, so the first while would display 1 and the second would display 2?

I know I could do it with $i++; but just wondered if there was an array function to do just this?

Not sure if I can use key with a foreach loop?

Upvotes: 0

Views: 972

Answers (4)

Igor Parra
Igor Parra

Reputation: 10348

I recommend you use foreach for almost all your array loops needs:

foreach ($sidebar as $single) {}

And for count array elements just use count()

count ($sidebar);

if (is_array($sidebar))
foreach ($sidebar as $key => $single) :
?>
    <h3><?php echo $key; ?></h3>
    <p><?php echo $single['title']; ?></p>
<?
endforeach;

Final solution:

if (is_array($sidebar))
{
    $i = 0;
    foreach ($sidebar as $key => $item)
    {
        $i2 = ++ $i;
        echo "<h3>{$i2}.- $key</h3>\n";

        if (is_array($item))
        {
            $j = 0;
            foreach ($item as $single)
            {
                $j2 = ++ $j;
                echo "<p>{$j2}.- {$single['title']}</p>";
            };
        }
    }
}

Upvotes: 0

Madbreaks
Madbreaks

Reputation: 19539

Oi - all those tags (and short tags at that) are painful to look at. Feels a lot like PHP 4, anyone forced to support this code isn't going to be very happy. No offense intended, but can I suggest something like:

$i = 0;

$sidebar = array(
    "Best of the Month" => $featuredBestMonth, 
    "Featured Content"  => $featuredContent
);

foreach($sidebar as $key => $item){
    if($item){   // will $item ever NOT evaluate to true?
        echo "<h3>".++$i.". $key</h3>";

        foreach($item as $single){
            echo "<p>$single[title]</p>";
        }
    }
}

I'm still not sure this code makes sense, but based on your example it should at least produce the same result (also not sure where you want your counter to be displayed, since your question isn't very clear..so I guessed).

Good luck.

Upvotes: 0

Danny
Danny

Reputation: 1185

I do not believe there is a way to do what you are asking with a string index (without of coursing using a separate counter variable). A for loop, or another loop with a counter is really the only way to do what you asked.

Upvotes: 0

Halcyon
Halcyon

Reputation: 57709

array_search(key($sidebar), array_keys($sidebar));

Hmm .. not pretty. Use a for loop? :P

Upvotes: 1

Related Questions