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

前端 未结 10 1717
陌清茗
陌清茗 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:38
    $i = 0;
    foreach ($arr as $key => $val) {
      if ($i === 0) {
        // first index
      }
      // current index is $i
    
      $i++;
    }
    
    0 讨论(0)
  • 2020-12-14 06:47

    You could get the first element in the array_keys() function as well. Or array_search() the keys for the "index" of a key. If you are inside a foreach loop, the simple incrementing counter (suggested by kip or cletus) is probably your most efficient method though.

    <?php
       $array = array('test', '1', '2');
       $keys = array_keys($array);
       var_dump($keys[0]); // int(0)
    
       $array = array('test'=>'something', 'test2'=>'something else');
       $keys = array_keys($array);
    
       var_dump(array_search("test2", $keys)); // int(1)     
       var_dump(array_search("test3", $keys)); // bool(false)
    
    0 讨论(0)
  • 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 '<br>';
    }
    
    0 讨论(0)
  • 2020-12-14 06:52

    $key is the index for the current array element, and $val is the value of that array element.

    The first element has an index of 0. Therefore, to access it, use $arr[0]

    To get the first element of the array, use this

    $firstFound = false;
    foreach($arr as $key=>$val)
    {
        if (!$firstFound)
           $first = $val;
        else
           $firstFound = true;
        // do whatever you want here
    }
    
    // now ($first) has the value of the first element in the array
    
    0 讨论(0)
提交回复
热议问题