Carter Roeser Carter Roeser - 15 days ago 5
PHP Question

Use set post value as php variable

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!

Answer

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'];
}
Comments