I'm working on a long, long user form which will then lead to a customized display.
The final display has to be curated, paragraph by paragraph, to fit the user's input.
My first attempt was all if statements:
if($input_a && $input_b && $input_c !== $input_d) :
echo result;
if($input_a === 'example') :
return false;
endif;
if($input_b !== 'example') :
echo $input_c * $input_d;
endif;
endif;
This got very messy, especially when I had to pass the results of this logic between JS and PHP.
My next attempt involved building a custom string for each user, based on some of the inputs ('x' means no input):
$code = array('x', 'x', 'x', 'x', 'x', 'x');
if($input_a && $input_b && $input_c !== $input_d) :
$code[0] = 1;
$code[1] = 1;
if($input_a === 'example') :
$code[2] = 1;
else:
$code[2] = 0;
endif;
if($input_b !== 'example') :
$code[3] = 1;
else :
$code[3] = 0
endif;
else :
$code[0] = 0;
$code[1] = 0;
endif;
So, in the above, the string would read something like '01x0'. Now I can assign the user this code, based on their input. Further along in the logic, I can check against this code to decide whether to serve some blocks of content or hide others.
If I want to check for a match on the first and fourth inputs, but don't care about the second and third, I can do this:
// 'x' is a placeholder for code items I don't care about
$result_option = '1xx1';
$pattern = '/[' . $code[0] . 'x][' . $code[1] . 'x][' . $code[2] . 'x]/';
if(preg_match($pattern, $result_option) :
echo $result_option;
endif;
Ok, so this works.
But I feel like I'm reinventing the wheel here and eventually my code string is going to be a hundred characters long.
Are there better ways to serve customized content based on hundreds of user options that doesn't involve a hundred classes of nested if statements?
Aucun commentaire:
Enregistrer un commentaire