I have two input fields in my form.
One is name and the other one is age.
As I enter values in the both fields, they should be stored in associative array. And it should prompt me to enter more names and ages as long the age is less or equal to 100.
How do I do that in php ?
PHP Associative Array
Moderator: General Moderators
Re: PHP Associative Array
You've already spelled out step by step what you need to do. What have you written so far? Where are you getting stuck?
Re: PHP Associative Array
Celauran wrote:You've already spelled out step by step what you need to do. What have you written so far? Where are you getting stuck?
Code: Select all
<input type = "text" name = "name">
<input type = "text" name = "age">
$name = $_POST['name']
$age = $_POST['age']
$list = array($name => $age);
foreach ($list as $key)
echo $key . '<br>';
- Christopher
- Site Administrator
- Posts: 13596
- Joined: Wed Aug 25, 2004 7:54 pm
- Location: New York, NY, US
Re: PHP Associative Array
You have two input fields in your example, but no form tags. I added them in the example below.yetin wrote:I have two input fields in my form.
One is name and the other one is age.
With associative arrays, we need to know what the key and value are. In your example, you are using the name as the key. is That what you want to do?yetin wrote:As I enter values in the both fields, they should be stored in associative array. And it should prompt me to enter more names and ages as long the age is less or equal to 100.
yetin wrote:How do I do that in php ?
Code: Select all
<!-- I added form tags. If you want the form page to post to itself, you can leave the action blank or put the the URL to this page -->
<form action="" method="post">
Name: <input type = "text" name = "name"><br>
Age: <input type = "text" name = "age"><br>
<input type = "submit" name = "Submit"> <!-- you also need a submit button -->
</form>
<!-- you need to put PHP tags here so the parser knows what is PHP and what is HTML -->
<?php
// you need to check if the user has submitted values
if (isset($_POST['name']) && isset($_POST['name'])) {
$name = $_POST['name'];
$age = $_POST['age'];
$list = array($name => $age);
// if you want both the key and the value, use => in foreach. Otherwise you will just get the value
foreach ($list as $key => $value ) {
echo "$key => $value<br>";
}
// PS - it is a good habit to always use braces for loop/conditional constructs. It reduces confusion/errors later.
} else {
echo "Please enter a name and age. ";
}
?>(#10850)