Page 1 of 1

PHP Associative Array

Posted: Fri Apr 03, 2015 7:27 am
by yetin
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 ?

Re: PHP Associative Array

Posted: Fri Apr 03, 2015 7:51 am
by Celauran
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

Posted: Fri Apr 03, 2015 10:18 am
by yetin
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>';

Re: PHP Associative Array

Posted: Fri Apr 03, 2015 2:59 pm
by Christopher
yetin wrote:I have two input fields in my form.
One is name and the other one is age.
You have two input fields in your example, but no form tags. I added them in the example below.
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.
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: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. ";
}
?>