PHP « Как узнать порядковый номер итерации в foreach/while

Код:
/** * GeSHi (C) 2004 - 2007 Nigel McNie, 2007 - 2008 Benny Baumann * (http://qbnz.com/highlighter/ and http://geshi.org/) */ .php.geshi_code {font-family:monospace;} .php.geshi_code .imp {font-weight: bold; color: red;} .php.geshi_code .kw1 {color: #b1b100;} .php.geshi_code .kw2 {color: #000000; font-weight: bold;} .php.geshi_code .kw3 {color: #990000;} .php.geshi_code .co1 {color: #666666; font-style: italic;} .php.geshi_code .co2 {color: #666666; font-style: italic;} .php.geshi_code .co3 {color: #0000cc; font-style: italic;} .php.geshi_code .co4 {color: #009933; font-style: italic;} .php.geshi_code .coMULTI {color: #666666; font-style: italic;} .php.geshi_code .es0 {color: #000099; font-weight: bold;} .php.geshi_code .es1 {color: #000099; font-weight: bold;} .php.geshi_code .es2 {color: #660099; font-weight: bold;} .php.geshi_code .es3 {color: #660099; font-weight: bold;} .php.geshi_code .es4 {color: #006699; font-weight: bold;} .php.geshi_code .es5 {color: #006699; font-weight: bold; font-style: italic;} .php.geshi_code .es6 {color: #009933; font-weight: bold;} .php.geshi_code .es_h {color: #000099; font-weight: bold;} .php.geshi_code .br0 {color: #009900;} .php.geshi_code .sy0 {color: #339933;} .php.geshi_code .sy1 {color: #000000; font-weight: bold;} .php.geshi_code .st0 {color: #0000ff;} .php.geshi_code .st_h {color: #0000ff;} .php.geshi_code .nu0 {color: #cc66cc;} .php.geshi_code .nu8 {color: #208080;} .php.geshi_code .nu12 {color: #208080;} .php.geshi_code .nu19 {color:#800080;} .php.geshi_code .me1 {color: #004000;} .php.geshi_code .me2 {color: #004000;} .php.geshi_code .re0 {color: #000088;} .php.geshi_code span.xtra { display:block; }
$answers = null;
  $answer_number = - 1;
  $answers_array = explode( '|', $row['answers'] );
  foreach ( $answers_array as $item ) {
    $answer_number = $answer_number + 1;
    if($answer_number === 0) $checked = 'checked="checked"';
    else $checked = null;
    $answers .= '<input class="poll_box_item" type="radio" '.$checked.' name="poll_answer" value="' . $answer_number . '" /> ' . $item . '<br />';
  }

в этом коде вычисляется номер варианта ответа(скрипт опроса) методом прибавления 1 к текущему значению переменной, но мне кажется это неверное решение, есть ли более элегантное и быстрое решение, также необходимо на самой первой итерации вставить в строку($answers) определенный параметр, сейчас это делается примерно через ту же жопу... В общем: как определить порядковый(от 0) номер итерации в foreach или while?

1 ответов


$answers = null;

  $answers_array = explode( '|', $row['answers'] );
  foreach ( $answers_array as $item ) {
   if(key($answers_array)== 0) $checked = 'checked="checked"';
    else $checked = null;
    $answers .= '<input class="poll_box_item" type="radio" '.$checked.' name="poll_answer" value="' . key($answers_array) . '" /> ' . $item . '<br />';
  }

возможно так будет тоже работать, не тестировал(по памяти)

Сразу напишу правильный код:

$answers = ""; // пишем не null, а пустую строку
  $answer_number = 0; // тут пишем 0, или любое число, не имеет значения. В цикле все равно изменяется
  $answers_array = explode( '|', $row['answers'] );
 
  /*
      $answers_array теперь имеет такую конструкцию
      Array (
          [0] => item1
          [1] => item2
          [3] => item3
          ... и т.д.
      )
   */


  foreach ( $answers_array as $key=>$item ) { // Добавляем $key - индекс ответа в $answers_array
    $answer_number = $key; // Тут присваиваем индекс к $answer_number. Это Вы
                          // можете пропустить и потом, вместо   $answer_number
                          // использовать $key. Я так написал, чтобы Вы поняли для чего это

    $checked = ""; // Тут говорим, что $checked - пустая строка. Если $answer_number будет 0, то строка изменится, в противном случае он остается пустой

    if($answer_number === 0) $checked = 'checked="checked"';

    // Строку я немножко изменил.
    $answers .= "<input class='poll_box_item' type='radio' $checked name='poll_answer' value=' $answer_number ' /> $item<br />";
  }

foreach ( $answers_array as $k => $v ) {
    $checked = !$k ? 'checked="checked"' : null;
    $answers .= '<input class="poll_box_item" type="radio" '.$checked.' name="poll_answer" value="' . $k . '" /> ' . $v . '<br />';
}

Судя по коду Вам надо отловить первый элемент в итерации.
Можно попробовать так:

<?php

$arr = array('asdasd','apple', 'wwasdasd', 'asdfasdf');

foreach ($arr as $d)
{
  if (prev($arr) !== false)
    echo 'first ('.$d.')<br/>';
  else
    echo $d.'<br/>';
  }
//output
first (asdasd)
apple
wwasdasd
asdfasdf


При использовании explode возвращается массив где ключем является индекс элемента, например результатом

explode(',', 'foo,bar'); будет
array( 0 => 'foo', 1 => 'bar')
Поэтому в вашем случае я думаю можно использовать этот индекс:

foreach ( $answers_array as $answer_number => $item ) {}