0

I'm currently trying to send an array as the value of an option in a select but I cannot access the data after the form is sent.

echo '<select id="domainResults_domaines" name="domainResults_domaines">';
foreach($domainsFound as $domain){
    echo '<option value="'.$domain.'">'.$domain['domaine'].'</option>';
}
echo '</select>';

The $domain array contains 2 values and I want to be able to access both of those after sending the form. Is there a way to send the array as the value or is there another way to pass 2 variables in a single option?

Thanks for the help.

2 Answers 2

1

Try:

echo '<select id="domainResults_domaines" name="domainResults_domaines">';
foreach($domainsFound as $key=>$value){
    echo '<option value="'.$key.'">'.$value.'</option>';
}
echo '</select>';

Check out PHP foreach.

Sign up to request clarification or add additional context in comments.

1 Comment

I used this method to pass the key as the value and added hidden inputs to pass my variables. This way I can use the key to get the correct hidden inputs for the domain chosen. Might not be the most effective way to do it but it works just fine.
1

Value has to be string, you could use something like json_encode to set the value and json_decode to get the array back on server side.

foreach($domainsFound as $domain){
    echo '<option value="'.htmlspecialchars(json_encode($domain)).'">'.$domain['domaine'].'</option>';
}

3 Comments

I just tried doing that and it removed the notices Array to string conversion in the source code. However, after I send the form, I do var_dump(json_decode($_POST['domainResults_domaines'])); but this gives me NULL.
Be careful with that. json_encode will regularly include ' and ".
@OlivierParenteau I added htmlspecialchars in the example, for proper escaping. If this won't work, and you only need the values, then try to do it like this: implode(',',array_values($domain)); And split this string on server it again.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.