How can I get the current array index in a foreach loop?

前端 未结 10 1719
陌清茗
陌清茗 2020-12-14 06:19

How do I get the current index in a foreach loop?

foreach ($arr as $key => $val)
{
    // How do I get the index?
    // How do I get the fir         


        
10条回答
  •  一生所求
    2020-12-14 06:28

    This is the most exhaustive answer so far and gets rid of the need for a $i variable floating around. It is a combo of Kip and Gnarf's answers.

    $array = array( 'cat' => 'meow', 'dog' => 'woof', 'cow' => 'moo', 'computer' => 'beep' );
    foreach( array_keys( $array ) as $index=>$key ) {
    
        // display the current index + key + value
        echo $index . ':' . $key . $array[$key];
    
        // first index
        if ( $index == 0 ) {
            echo ' -- This is the first element in the associative array';
        }
    
        // last index
        if ( $index == count( $array ) - 1 ) {
            echo ' -- This is the last element in the associative array';
        }
        echo '
    '; }

    Hope it helps someone.

提交回复
热议问题