Jump to content

If statements to assign POST variables


Omzy

Recommended Posts

you can use the ternary operator

 $name = (isset($_POST['name'])) ? $_POST['name'] : null;

 

but thats not much better. Assuming you want to always check if the post variable is set before you assign it to a variable, i don't see a better way than an if statement

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.

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

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.