Brandon
Brandon

Reputation: 13

Array starting at Zero

Why doesnt this work? I need it to start out at 1 instead of 0. And if I change $i to = 1 then it doesnt grab the first row.
http://www.mcregister.com/beta/test.php

<?php  
if(isset($_POST['question'])) {  
   for ($i=0; $i<count($_POST['question']);$i++) {  
      $question=$_POST['question'][$i]."<br />"; echo "<b>Question $i:</b> $question";  
   }    
}  
?>

EDIT: Instead of starting out at 1.. I just need it to echo starting with "Question 1:" instead of "Question 0:".

Upvotes: 0

Views: 4937

Answers (5)

mesch
mesch

Reputation: 195

If all you want to do is output each question (without any validation!) you don't need the question variable at all. Just do:

echo 'Question #' . ($i + 1) . ': ' . $_POST['question'][$i];

Upvotes: 1

Thurein Soe
Thurein Soe

Reputation: 178

It's seem like you would like to get output

<b>Question 1:</b> Blah Blah

But. The array key is start from 0 by default

There have 2 way to get it. If you really want an array start with key number 1 . you can do by following code.

$new_array = array();
for ($i=0; $i<count($_POST['question']);$i++) {  
      $new_array[$i+1] = $_POST['question'][$i];  
} 

but if you want to have just 1. you can do like

if(isset($_POST['question'])) {  
   for ($i=0; $i<count($_POST['question']);$i++) {  
      $question=$_POST['question'][$i]."<br />"; echo "<b>Question ".$i+1.":</b> $question";  
   }    
}

Hope it's helpful.

Upvotes: 0

ThorDozer
ThorDozer

Reputation: 104

For all the answers here.. and i'm sure they know it.. for logical and simple reason, start your array at zero. Because.. like Russel Dias says: all array start at 0. If you don't want to make it complicated, start it at 0.

A high recommandation of all programmers :D Good Luck!

Upvotes: 0

Russell Dias
Russell Dias

Reputation: 73302

All array keys, by default, begin at index 0 (unless explicitly stated), therefore starting at 1 will not include the first result.

Upvotes: 3

zerkms
zerkms

Reputation: 254916

If you need posted data started with 1 (which is pointless actually) you have to change your html from

<input type="text" name="question[]" class="text">

to

<input type="text" name="question[1]" class="text">

etc

Upvotes: 1

Related Questions