How to submit an associative array with HTML & PHP

This post will show you how to submit an associative array with HTML and PHP. This concept is quite useful when you need to submit array-type data such as shopping cart information.

Feel free to skip to ‘HTML forms and input‘ or to ‘Submitting Array data through HTML‘ if you’re quite familiar with the syntax of PHP’s array() function.

YouTube player

Associative arrays in PHP

One of the best things about PHP is its dictionary-like arrays. The associative array data structure allows the user to create multi-dimensional arrays with many different data types. It is quite similar to an object but created at runtime. The values in associative arrays exist in key-value pairs.

As described on php.net:

“An array in PHP is actually an ordered map. A map is a type that associates values to keys.”

The code below shows how you can define a simple PHP array:

<?php
// For one dimensional array
$arr = array('hello', 'world', 12, 33.56); // notice different data types in the same array 

// Associative array structure using integer keys
$arr = array (  0 => 'value1', 1=>'value2');

// Or use strings as keys
$arr = array(
'key1' => 'value1',
'key2' => 'value2'
);

Notice that the keys are either integers or strings. In PHP arrays, the keys must be unique for each value, hence forming key-value pairs.

The code above shows only a basic version definition of a PHP array. To give a better understanding of what the array function is capable of, check out the code below:

<?php
$arr = array(
    'key' => 'value', // String 
    'age' => 25, // integer
    'score' => 87.12, // float
    'trx' => array(33, 55, 75, 113, 180), // one dimentional array
    'orderDetails' => array( // here we have a multidimentiional array as a value
        'name' => 'john doe',
        'productIDs' => array(11, 442, 532, 1341),
        'totalPrice' => 112.53,
        'currency' => 'USD'
    ),
    'myMethod' => function(){
        return "Hello, World!"
    }
);

// To individual access the values:
echo $arr['key']; // Prints value
echo $arr['age']; // Prints 25
echo $arr['score']; // Prints 87.12
echo $arr['trx'][2]; // Accesses 3rd value in the array, prints 75
echo $arr['orderDetails']['name']; // Prints john doe
echo $arr['orderDetails']['productIDs'][0]; // prints 11
echo $arr['myMethod'](); // Executes myMethod function; prints Hello, World!

By now, you might have a basic understanding of how PHP arrays work. Next, we’ll look into the HTML <form> and <input> tags and how we can use these to input array-like data from the user.

HTML forms and input

When it comes to the web, the standard way of submitting any input data taken from a user is through HTML <form> and <input> tags. We will be concentrating on the name attribute of the <input> tags.

The basic syntax for writing name values is:

form.html:

<form action="results.php" method='post'>
    <input type='text' name='genre'>
    <input type='number' name='year'>
    <button type='submit' name='submit'>Submit Form</button>
</form>

results.php:

<?php
$genre = $_POST['genre'];
echo $genre;

After the user clicks the submit button in the above code, the form data is sent to the results.php file. Since we used the POST method to submit the form, the results are stored in the $_POST array. We can access the data of the input field by using $_POST[’genre’]. Here genre is the value we used in the name attribute of the <input> tag. Let’s now look at an example. We can submit an array of data.

Submitting Associative Array data With HTML & PHP

Suppose you have multiple car names and want to receive them on the back-end as an array instead of name-value pairs for each car. You can achieve this by using the array notation like car[].

Let’s look at an extended example of the same problem.

form.html:

<form action='results.php' method='post'>
    <input name='cars[]' placeholder='Enter Car Name'>
    <input name='cars[]' placeholder='Enter Car Name'>
    <input name='cars[]' placeholder='Enter Car Name'>
    <input name='cars[]' placeholder='Enter Car Name'>
    <input name='cars[]' placeholder='Enter Car Name'>
    <button name='subimt'>Submit Information</button>
</form>

results.php:

<?php
$cars = $_POST['cars'];
foreach($cars as $car):
    echo $car."<br>";
endforeach;

print_r($cars);

Sample output:

Ferrari Testarossa
Lamborghini Gallardo
Ford Mustang
Honda Prius
Jeep Gladiator

Array
(
    [0] => Ferrari Testarossa
    [1] => Lamborghini Gallardo
    [2] => Ford Mustang
    [3] => Honda Prius
    [4] => Jeep Gladiator
)

In the above, you’ll notice that we only accessed one element in the $_POST array, i.e. carsTo access all the results at once. Using this method may be especially helpful when you are creating fields dynamically. You may even extend the above problem to allow car information and driver information as well.

form.html:

<form action="test.php" method="post">
	Enter Car 1 details: <br>
	<input type="text" name="cars[0][name]" placeholder="Enter car name">
	<input type="number" name="cars[0][year]" placeholder="Enter car year">
	<br><br>

	Enter Car 2 details: <br>
	<input type="text" name="cars[1][name]" placeholder="Enter car name">
	<input type="number" name="cars[1][year]" placeholder="Enter car year">
	<br><br>

	Enter Car 3 details: <br>
	<input type="text" name="cars[2][name]" placeholder="Enter car name">
	<input type="number" name="cars[2][year]" placeholder="Enter car year">
	<br><br>

	<button type="submit">Submit Information</button>
</form>

results.php:

<?php
print_r($_POST);

Sample output:

Array ( 
    [cars] => Array ( 
        [0] => Array ( 
            [name] => Jeep Gladiator 
            [year] => 2019 
        ) 
        [1] => Array ( 
            [name] => Ford Mustand Vintage 
            [year] => 1966 
        ) 
        [2] => Array ( 
            [name] => Ferrari Testarossa 
            [year] => 1990 
        )
    )
)

Wrapping up

As you can see, an associative array is formed on the server side. Using this method, you can submit many combinations of data. You can also use this method to get information from fields dynamically added to your form.

Examples can include:

  • Adding a new education/degree field upon button press
  • Adding a new products row when working on a point-of-sale (POS) system.
  • Reading multiple products and their info from newly added products.

You may also be interested in

About Anto Online

Anto, a seasoned technologist with over two decades of experience, has traversed the tech landscape from Desktop Support Engineer to enterprise application consultant, specializing in AWS serverless technologies. He guides clients in leveraging serverless solutions while passionately exploring cutting-edge cloud concepts beyond his daily work. Anto's dedication to continuous learning, experimentation, and collaboration makes him a true inspiration, igniting others' interest in the transformative power of cloud computing.

View all posts by Anto Online

One Comment on “How to submit an associative array with HTML & PHP”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.