Obtaining the key and values ​​from a multidimensional array in a foreach loop (PHP / HTML)


I have a multidimensional array where each entry looks like the following:

$propertiesMultiArray['propertyName'] = array(
    'formattedName' => 'formattedNameValue',
    'example' => 'exampleValue',
    'data' => 'dataValue');

I have a form in which I want to use a foreach loop to fill up values and input field characteristics, using the key from the outer array as well as the different information stored in the inner array. All values would be used as strings. So far, I have

foreach($propertiesMultiArray as $key => $propertyArray){
    echo "<p>$propertyArray['formattedName'] : " .
    "<input type=\"text\" name=\"$key\" size=\"35\" value=\"$propertyArray['data']\">" .
    "<p class=\"example\"> e.g. $propertyArray['example'] </p>" .

I would like the HTML segment to resemble the following:

formattedNameValue : dataValue
e.g. exampleValue

where dataValue is in a input text field and $key is used as the name to submit that input to the form. Essentially I want $key = "propertyName". However, it gives the following error:

syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING)

How can I access the information from the inner array of the multidimensional one but obtain the key at the same time?

There are quite a few different ways to handle this. One option is to use the complex string syntax like this:

foreach($propertiesMultiArray as $key => $propertyArray) {
    echo "<p>{$propertyArray['formattedName']} : " .
    "<input type=\"text\" name=\"$key\" size=\"35\" value=\"{$propertyArray['data']}\">" .
    "<p class=\"example\"> e.g. {$propertyArray['example']} </p>" .

Another option is to set up your HTML as a format string and output it with your variables using printf

$format = '<p>%s : <input type="text" name="%s" size="35" value="%s">
           <p class="example"> e.g. %s </p><br><br></p>';
foreach($propertiesMultiArray as $key => $propertyArray) {
    printf($format, $propertyArray['formattedName'], $key,
           $propertyArray['data'], $propertyArray['example']);

(By the way, I noticed when I was writing the printf example that your HTML has a paragraph inside a paragraph. I don't believe this is valid HTML.)