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.
Watch the video on YouTubeAssociative 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