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

前端 未结 10 1732
陌清茗
陌清茗 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:51

    based on @fabien-snauwaert's answer but simplified if you do not need the original key

    $array = array( 'cat' => 'meow', 'dog' => 'woof', 'cow' => 'moo', 'computer' => 'beep' );
    foreach( array_values( $array ) as $index=>$value ) {
    
        // display the current index +  value
        echo $index . ':' . $value;
    
        // 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 '
    '; }

提交回复
热议问题