How do I echo this?

I've got a loop of select statements that look like this:

<select name="1"></select>
<select name="2"></select>
<select name="3"></select>

<input type="hidden" name="count" value="3">

Then, when I attempt to process the form, I'm doing something like this:

$the_count=$_POST['final_count'];
$number=1;
for($x=1; $x<=$the_count; $x++)
{
      echo $_POST[$number];
      echo "<br>";
      $number=$number+1;
}

...it doesn't work. I get an error that says I have an undefined offset.

How can I get this to work?
Bruce GustPHP DeveloperAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Kim WalkerWeb Programmer/TechnicianCommented:
Do you have an input element with the name "final_count"? You have not included it in the code you have provided.

BTW, it would help us a great deal if you would isolate your code by selecting it, then click the "CODE" button in the menu bar at the top of the comment window before submitting your comment or question. It makes it easier for us to recognize which is code and which is comment.
Scott FellDeveloper & EE ModeratorCommented:
You have final_count in your php but your html you have count
Dave BaldwinFixer of ProblemsCommented:
Yep.
<input type="hidden" name="count" value="3">
...
$the_count=$_POST['final_count'];

Open in new window

Your Guide to Achieving IT Business Success

The IT Service Excellence Tool Kit has best practices to keep your clients happy and business booming. Inside, you’ll find everything you need to increase client satisfaction and retention, become more competitive, and increase your overall success.

Ray PaseurCommented:
I see a few things that matter.

Arrays* are indexed from zero in PHP (and almost every other modern programming language).  Strings, too.  So the last (highest) numerical array index is computed by taking count() and subtracting one.

HTML forms have <input> controls.  A name= attribute is part of the control.  The name becomes the associative array key in the request arrays ($_GET / $_POST).  If you omit the name= attribute, the input control will not be present in the request arrays.  If you have duplicate name= attributes, PHP will present the last element in the request arrays, however the other elements may be found in the raw request data.

The correspondence between name= attributes in HTML and associative array keys in the request variables is 1:1 and case-sensitive.

PHP request variables are best handled as associative arrays, so counting and enumerating with for() is rarely a good design idea -- it tends to lead to complex and brittle / buggy code.  You can use foreach() much more easily.  It accounts nicely for the computer science principle that there are three numbers that matter: zero, one, and infinity.

Here is a script you can experiment with.  Try a few different selections and see what you get!
http://iconoun.com/demo/temp_brucegust.php
<?php // demo/temp_brucegust.php
/**
 * http://www.experts-exchange.com/questions/28934907/How-do-I-echo-this.html
 *
 * References:
 * http://php.net/manual/en/tutorial.forms.php
 */
error_reporting(E_ALL);

// IF THERE IS A POST-REQUEST
if (!empty($_POST))
{
    // SHOW ALL THE REQUEST VARIABLES
    echo '<pre>';
    echo '_POST: ';
    var_dump($_POST);

    // SHOW HOW TO ITERATE OVER AN ARRAY OF REQUEST VARIABLES
    $kount = 0;
    foreach ($_POST['mySelectControlArray'] as $value)
    {
        if (!empty($value))
        {
            $kount++;
            echo PHP_EOL . "This value was selected: $value";
        }
    }
    echo PHP_EOL . "The total number of selections is: $kount";
    echo '</pre>';
}

// END OF PHP, PUT UP THE HTML DOCUMENT
?>
<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<head>
<meta charset="utf-8" />
<meta name="robots" content="noindex, nofollow" />

<title>Form Example: demo/temp_brucegust</title>
</head>

<body>
<form method="post">

<!-- Square brackets create array notation in the request vars -->
<select name="mySelectControlArray[]" multiple>
<option value="0" selected>Please Choose (one or more)</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Tre</option>
<option value="4">For</option>
</select>

<!-- No "name=" attribute means that this control will not show up in the PHP script -->
<input type="submit" value="Submit the Form" />

<!-- "hidden" controls are just like "input" controls, but are pre-filled in the HTML document -->
<!-- Only the last value will be presented for each "name=" attribute -->
<input type="hidden" name="Bruce" value="Not" />
<input type="hidden" name="Bruce" value="This" />
<input type="hidden" name="Bruce" value="Gust" />
</form>

</body>
</html>

Open in new window


* Required reading for all PHP programmers!

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Chris StanyonWebDevCommented:
An alternative approach is to use a foreach loop. Just name your <select> elements as an array:

<form method="post">
	<select name="mySelect[]">
		<option value="a1">a1</option>
		<option value="a2">a2</option>
		<option value="a3">a3</option>
	</select>

	<select name="mySelect[]">
		<option value="b1">b1</option>
		<option value="b2">b2</option>
		<option value="b3">b3</option>
	</select>

	<select name="mySelect[]">
		<option value="c1">c1</option>
		<option value="c2">c2</option>
		<option value="c3">c3</option>
	</select>

	<input type="submit" value="Submit">
</form>

Open in new window

And then loop through them with a foreach:

<?php
	foreach ($_POST['mySelect'] as $value) {
		echo $value . "<br>";
	}
?>

Open in new window

Vimal DMSenior Software EngineerCommented:
HI,
Your select box structure should be like this so that you can get the selected values in the post page, name as array will help to get the radion,checkbox and multi select boxes values on the post page,

<select name="final_count[]">
		<option value="1">1</option>
		<option value="2">2</option>
		<option value="3">3</option>
</select>

Open in new window

Bruce GustPHP DeveloperAuthor Commented:
Thanks, guys! I've been able to glean some wisdom from more than one question and we're making progress. If you're willing, the next "snag" is represented by http://www.experts-exchange.com/questions/28937356/I'm-using-JQuery-I'm-submitting-a-form-and-opening-up-a-sidebar-How.html and I would welcome your input. Thanks!
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.