samayo
samayo

Reputation: 16495

How to pass a couple of posted values through a function

Ok, the title does not describe the problem, but here is my form inside a function.

function register(){
  echo "
   <input type='text' name='username' value='' />
   <input type='text' name='email'  value='' />
   <input type='text' name='lastname' value='' />
   ";
}

Here, is what I want: If a user submits a form, I want inputs to keep the values instead of the input being empty. But, if the form was not inside a function, I could do something like this

echo "<input type='text' name='username' value='".if(isset($_POST['username'])){echo $_POST['username']}."' />"

but, since this is inside a function, and there are more than one inputs, I want to find a way, to keep the inputs and pass them through the argument like

echo register($submittedArguments)

Upvotes: 0

Views: 56

Answers (1)

Stoic
Stoic

Reputation: 10754

Since, $_POST is a global variable, you can use it directly inside your function.

Therefore, you can do something like this:

function register(){
  echo "
   <input type='text' name='username' value='".if(isset($_POST['username'])){echo $_POST['username']}."' />
   <input type='text' name='email' value='".if(isset($_POST['email'])){echo $_POST['email']}."' />
   <input type='text' name='lastname' value='".if(isset($_POST['lastname'])){echo $_POST['lastname']}."' />
   ";
}

If you specifically want to pass variables to your function, you can do something like this:

// the following will create variables based on the key names of the $_POST array.
// this means, $_POST['username'] = "me", will create a variable $username = "me"
// beware that this can create unwanted variables and behaviour
extract($_POST); 

// otherwise, you can manually assign variables one by one, like this:
//   $username = $_POST['username']
// .. and so on..

function register($username = "", $email = "", $lastname = ""){
  echo "
   <input type='text' name='username' value='".echo $username."' />
   <input type='text' name='email' value='".echo $email."' />
   <input type='text' name='lastname' value='".echo $lastname."' />
   ";
}

Upvotes: 1

Related Questions