-2

I would like to be able to assign the name of a variable outside the function so that the function can assign the chosen variable. It does not seem to work. Anyone have any ideas?

Below is my attempt, however the $admin variable is empty after running the function.

function assign_check($variable, $check) {
    if (empty($_POST[$check])) {
        $variable = "no";   
    } else {
        $variable = $_POST[$check];
    }       
}

assign_check('$admin', 'admin');

My question is not about the use of global variables.

Roelof Coertze
  • 586
  • 3
  • 15

2 Answers2

1

You can request a reference in the function body.

function assign_check(&$variable, $check) {
     $variable = 'hello';
}

And call passing a variable (reference).

assign_check($admin, 'admin');

$admin value is now 'hello';

Fitting that to your code would result in

function assign_check(&$variable, $check) {
    $variable = empty($_POST[$check]) ? "no" : $_POST[$check];
}

assign_check($admin', 'admin');

But returning a proper value would be much cleaner code than using references. Using a ternary operator like presented above would it even simplify without need of a function at all.

Markus Zeller
  • 8,516
  • 2
  • 29
  • 35
  • 2
    Because it bears repeating "But returning a proper value would be much cleaner code than using references." Don't use references unless you have a compelling reason to, and nothing here represents a good reason. @roelofco – jfadich Sep 09 '19 at 22:40
1

A normal way to assign the result of a function to a variable name specified outside the function would be to have the function return the result and assign it directly to the variable when you call the function.

function assign_check($check) {
    if (empty($_POST[$check])) {
        return "no";   
    } else {
        return $_POST[$check];
    }       
}

$admin = assign_check('admin');

I would do it this way unless there was a compelling reason to do it otherwise.

For the specific type of thing it looks like this function is intended to do, I would suggest looking at filter_input.

Don't Panic
  • 41,125
  • 10
  • 61
  • 80