Carter Roeser
Carter Roeser

Reputation: 360

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!

Upvotes: 0

Views: 1050

Answers (2)

Nico
Nico

Reputation: 2663

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

Upvotes: 1

Nytrix
Nytrix

Reputation: 1139

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. 
}
?>

Upvotes: 0

Related Questions