Jump to content

If statements to assign POST variables


Omzy

Recommended Posts

I find myself doing this a lot of the time:

 

if(isset($_POST['name'])) $name=$_POST['name'];

 

I get the feeling there is a simpler way of doing this. It's not such a bother if it's just one or two but its when you have a whole bunch of these that it gets tedious!

Link to comment
Share on other sites

One alternative, have an array of form element names then loop through that assigning the data.

 

$validElements = array("name", "email", "user", "password");

foreach ($validElements as $val) {
       $$val = isset($_POST[$val]) ? $_POST[$val] : null;
}

 

Which way is better is up to you to decide.

Link to comment
Share on other sites

You could create a function

 

<?php

function setValue (&$variable, $default)
{
    return (isset($variable)) ? $variable : $default;
}

//Set values for testing only
$foo['bar1'] = 'Passed Value';
//$foo['bar2'] = 'Passed Value'; //This value not set


$bar1 = setValue($foo['bar1'], 'Value not set');
$bar2 = setValue($foo['bar2'], 'Value not set');

echo "bar1 = $bar1";  //Output: bar1 = Passed Value
echo "bar2 = $bar2";  //Output: bar2 = Value not set

?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.