1

Is it possible to store multiple textbox values in array, i have N number of textboxes

<input type="text" name="grade[]" id="grade" />
<input type="text" name="grade[]" id="grade" />
<input type="text" name="grade[]" id="grade" />

i tried this code to add all the text box value but it returns only the last text box value.

    $grade=$_POST['grade'];
for($i=1;$i<=3;$i++)
{
    $per=$grade[$i]*$grade[$i];
    echo $per;
}
2
  • 2
    Try var_dump($_POST['grade']) to get an idea of what is being passed to your PHP. Commented Aug 15, 2012 at 10:32
  • 1
    how can you set same id to all text boxes? Commented Aug 15, 2012 at 10:35

3 Answers 3

2

Besides of starting on 0, it should finish on 2 if you have 3 text boxes.

for($i=0;$i<=2;$i++)
{
  $per=$grade[$i]*$grade[$i];
  echo $per;
}

Or you could use the array length if you don't want to hardcode the number of iteractions. This should work:

for($i=0;$i<=count($grade)-1;$i++)
{
  $per=$grade[$i]*$grade[$i];
  echo $per;
}

EDIT

This should work too and it's slightly cleaner (avoiding the -1) and using the pow() function:

for($i=0;$i<count($grade);$i++)
{
  echo pow($grade[$i], 2);
}
Sign up to request clarification or add additional context in comments.

2 Comments

well $i < 3 will stop at 2 just the same as $i <= 2 will.
@Rawb92 I didn't see it when I wrote it, I saw it later, I just kept it in the question format with <=. Edited it. Also added the pow function.
2

Try this one...

<?php

    foreach ($_GET['grade'] as $grade){
        $per = $grade * $grade;
        echo $per;
    }

?>

Comments

0

Try using this

$per='';
$grade=$_POST['grade'];
for($i=0;$i<count($grade);$i++)
{
    $per .=$grade[$i]*$grade[$i];
    $per .='<<>>';
}
 echo $per;

count($grade) is used for n no. of textboxes. You need to concatenate the values of variable in order to get the values of all the textboxes.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.