0

I have a HTML form which looks like this...

<input type="checkbox" name="comp[{url_title}][check]" value="Yes" class="checkbox" />
{if question}<input type="text" name="comp[{url_title}][answer]" value="" />{/if}

<input type="checkbox" name="comp[{url_title}][check]" value="Yes" class="checkbox" />
{if question}<input type="text" name="comp[{url_title}][answer]" value="" />{/if}

<input type="checkbox" name="comp[{url_title}][check]" value="Yes" class="checkbox" />
{if question}<input type="text" name="comp[{url_title}][answer]" value="" />{/if}

my vardump on $_POST looks like this...

array(3) {
  ["some-competition-title"]=>
  array(1) {
    ["check"]=>
    string(3) "Yes"
  }
  ["third-competition"]=>
  array(2) {
    ["check"]=>
    string(3) "Yes"
    ["answer"]=>
    string(6) "asdasd"
  }
  ["another-comp-title"]=>
  array(1) {
    ["check"]=>
    string(3) "Yes"
  }
}

and my foreach loop looks like this

foreach ($_POST['comp'] as $topkey => $input) {
    foreach ($input as $key => $value) {

        echo "<div style=\"background:#fff; padding:10px;\">";
        echo "$topkey | $value ";
        echo "<br>";
        echo "</div>";

    }
}

which will return

some-competition-title | Yes 
third-competition | Yes 
third-competition | asdasd 
another-comp-title | Yes 

OK - I'm trying to pass the foreach loop so it will combine the checkbox and the answer if the name of the array (url-title) is the same, so essentially I would like it to return this.

some-competition-title | Yes 
third-competition | Yes | asdasd 
another-comp-title | Yes 

Opposed to what I have above. Any help would be really appreciated. Thanks.

2 Answers 2

1

You simply need to combine the subarray values into one value.

foreach ($_POST['comp'] as $topkey => $input) 
{
    // get the values of the subarray and assign them
    // to $value 
    $value = implode(' | ', array_values($input));

    echo "<div style=\"background:#fff; padding:10px;\">";
    echo "$topkey | $value ";
    echo "<br>";
    echo "</div>";
}
Sign up to request clarification or add additional context in comments.

Comments

1

How about using one for loop:

foreach ($_POST['comp'] as $topkey => $input) {
    echo "<div style=\"background:#fff; padding:10px;\">";
    $value = '';
    if (isset($input['check']) && isset($input['answer'])) {
        $value = $topkey . " | " . $input['check'] . " | " . $input['answer'];
    } elseif (isset($input['check'])) {
        $value = $topkey . " | " . $input['check'];
    }
    echo "$topkey | $value ";
    echo "<br />";
    echo "</div>";
}

You check whether both check and answer is present in the array, if yes the first if condition is true and value is taken, else if only check is present, the elseif executes.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.