Longblog
Longblog

Reputation: 849

define constant using if isset

I have an array of constants I'm using to populate an array of params. The code looks something like this:

define( 'variable_one', $_POST["variable_one"];
define( 'variable_two', $_POST["variable_two"];

$current_api_params->sVariableOne = variable_one;
$current_api_params->sVariabletwo = variable_two;

How do I set one of the constants through an if statement? The variables are coming from a form, and given the form options, variable_one, or two or any of the dozens I'm working with, might be a number of different names.

Do I just do something like

if ( isset($_POST["variable_one"] ) {
  define( 'variable_one', $_POST["variable_one"] );
}
elseif ( isset($_POST["variable_one_different_name"] ) {
  define( 'variable_one', $_POST["variable_one_different_name"] );
}
else {
  define( 'variable_one', '' );
}

$current_api_params->sVariableOne = variable_one;

If that's how it is done, is there a shorthand for it? All this typing is getting tedious!

Upvotes: 0

Views: 310

Answers (1)

Don Djoe
Don Djoe

Reputation: 705

You can use array_keys and for loop

Somewhere along these lines (you might need to check some syntax error, as I'm typing this without any IDE/proper environment)

$keys = array_keys($_POST)
foreach ($keys as $keyItem)
{
    define($keyItem, $_POST[$keyItem]);
}

Though I'm not sure why constants are not constant at all ... but hey that's up to you to decide.

Upvotes: 1

Related Questions