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

前端 未结 10 1716
陌清茗
陌清茗 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 '<br>';
    }
    

    Hope it helps someone.

    0 讨论(0)
  • 2020-12-14 06:30

    You can get the index value with this

    foreach ($arr as $key => $val)
    {
        $key = (int) $key;
        //With the variable $key you can get access to the current array index
        //You can use $val[$key] to
    
    }
    
    0 讨论(0)
  • 2020-12-14 06:31

    well since this is the first google hit for this problem:

    function mb_tell(&$msg) {
        if(count($msg) == 0) {
            return 0;
        }
        //prev($msg);
        $kv = each($msg);
        if(!prev($msg)) {
            end($msg);
    
            print_r($kv);
            return ($kv[0]+1);
        }
        print_r($kv);
        return ($kv[0]);
    }
    
    0 讨论(0)
  • 2020-12-14 06:33
    foreach($array as $key=>$value) {
        // do stuff
    }
    

    $key is the index of each $array element

    0 讨论(0)
  • 2020-12-14 06:37

    The current index is the value of $key. And for the other question, you can also use:

    current($arr)
    

    to get the first element of any array, assuming that you aren't using the next(), prev() or other functions to change the internal pointer of the array.

    0 讨论(0)
  • 2020-12-14 06:38

    In your sample code, it would just be $key.

    If you want to know, for example, if this is the first, second, or ith iteration of the loop, this is your only option:

    $i = -1;
    foreach($arr as $val) {
      $i++;
      //$i is now the index.  if $i == 0, then this is the first element.
      ...
    }
    

    Of course, this doesn't mean that $val == $arr[$i] because the array could be an associative array.

    0 讨论(0)
提交回复
热议问题