0

In a form I have a radio, of which one value is a specific API Key and the other radio opens a text input to enter a custom api key.

In order to distinguish from the two inputs in the action, they are set under different names.

My question is how do I set a PHP variable to equal the post value that is not empty.

For example, if input "a" has a set value then $apikey = $_POST['a'] but if "a" is empty and "p" has a value then $apikey = $_POST['p']

Here is the code used in the form for the two values that will be used:

<input type="radio" name="a" id="apibeta" value="###APIKEY###" onclick="javascript:hide();" required />

<input id='yes' name="p" class="form-control" placeholder="Personal API Key" type="text">

Thank you for any help!

2 Answers 2

1

Using the ternary operator:

$apiKey = !empty($_POST['a']) ? $_POST['a'] : $_POST['p'];

Which is equivalent to:

if (!empty($_POST['a'])) {
    $apiKey = $_POST['a'];
} else {
    $apiKey = $_POST['p'];
}
Sign up to request clarification or add additional context in comments.

2 Comments

I would have thought @Nytrix answer was better as it deals with the case where $_POST['p'] and $_POST['a] are both empty. A condition that could happen.
In that case $apiKey will end up being empty as well, which in many cases would be ok. If we're making assumptions I'd also say that sending an API key using a form probably isn't a good idea in the first place. But this is getting further and further away from the original question ;)
0

That is what if statements are for or switch statements.

Here is an example with your problem

<?php
if(isset($_POST['a'])){
    //do something with that
}elseif(isset($_POST['p'])){
    //p has the value
}else{
    //neither have a value. 
}
?>

Comments

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.