So this all stemmed from not wanting to check each POST in a huge If statement with tons of ANDs like so:
if(isset($_POST[$question], $_POST[$choice1], $_POST[$choice2], $_POST[$choice3], $_POST[$choice4], $_POST[$choice5], $_POST[$password]) &&
strlen(question > 0) &&
strlen(choice1 > 0) &&
strlen(choice2 > 0) &&
strlen(choice3 > 0) &&
strlen(choice4 > 0) &&
strlen(choice5 > 0) &&
strlen(password > 0))
{
$cat=$_POST['cat'];
$question=$_POST['question'];
$choice1=$_POST['choice1'];
$choice2=$_POST['choice2'];
$choice3=$_POST['choice3'];
$choice4=$_POST['choice4'];
$choice5=$_POST['choice5'];
$password=$_POST['password'];
}
else{
//Incorrect password or missing data
}
Instead I created an array with a string for each variable I wanted to check for and a foreach loop to run my tests
//create array with all wanted variables
$variables = array('cat', 'question', 'choice1', 'choice2', 'choice3', 'choice4', 'choice5', 'password');
$returnError = FALSE;
//run through array to check that all have been posted and meet requirements
foreach($variables as $var) {
if(!isset($_POST[$var]) || !strlen($_POST[$var]) > 0) {
$returnError = TRUE;
break;
}
}
Now I want to take the string names and instantiate variables with the same name
//create array with all wanted variables
$variables = array('cat', 'question', 'choice1', 'choice2', 'choice3', 'choice4', 'choice5', 'password');
$returnError = FALSE;
//run through array to check that all have been posted and meet requirements
foreach($variables as $var) {
if(!isset($_POST[$var]) || !strlen($_POST[$var]) > 0) {
$returnError = TRUE;
break;
}
else{
global $*/variable named $var*/ = $_POST[$var];
}
}
Is that possible? If not, how would I do something similar with an array of variables like so:
$variables = array($cat,$question,$choice1,$choice2,$choice3,$choice4,$choice5,$password);
You can use Variable variables, although it is not recommended.
global $$var = $_POST[$var];
Use eval(); http://www.php.net/eval
Be aware that creating variable with eval() from post data could be a security risk.