If I have 20 user input vars and want to work between $var[0..19], $_SESSION['var'[0..19]], & $_POST['var'[0..19]], such as:
$var0 = $_SESSION['var0'] = $_POST['var0'];
How could I do this efficiently using arrays and foreach loops?
Additional details:
So initially I have been thinking to try something like:
$inputVars = array('var1'=>$var1, 'var2'=>$var2, 'var3'=>$var3, 'var4'=>$var4, 'var5'=>$var5)
$inputVarsS = array($_SESSION['inputVars = array('svar1'=>$_SESSION['var1']'], 'svar2'=>$_SESSION['var2'], 'svar3'=>$_SESSION['var3'], 'svar4'=>$_SESSION['var4'], 'svar5'=>$_SESSION['var5'])
$inputVarsP = array($_POST['inputVars = array('pvar1'=>$_POST['pvar1']'], 'pvar2'=>$_POST['pvar2'], 'pvar3'=>$_POST['pvar3'], 'pvar4'=>$_POST['pvar4'], 'pvar5'=>$_POST['pvar5'])
and then I guess I could do something like:
$inputVarsS['svar1'] = $inputVarsP['pvar1'];
to set session value svar1 to posted value pvar1. But I am thinking there really must be a more efficient way to do these kinds of assignments.
I think I could just easily have $inputVars array and assign either POST SESSION values to the keys, but what if I want to have POST and SESSION values available simultaneously? Then I assume I need multiple arrays?
forEach LoopIt is faster in performance. It is slower than the traditional loop in performance. The break statement can be used to come out from the loop. The break statement cannot be used because of the callback function.
forEach is almost the same as for or for..of , only slower. There's not much performance difference between the two loops, and you can use whatever better fit's the algorithm. Unlike in AssemblyScript, micro-optimizations of the for loop don't make sense for arrays in JavaScript.
As it turned out, FOREACH is faster on arrays than FOR with length chasing. On list structures, FOREACH is slower than FOR. The code looks better when using FOREACH, and modern processors allow using it. However, if you need to highly optimize your codebase, it is better to use FOR.
You can use $$ to define a variable name, but I think it's better to use an array $vars.
With $var0, $var1, ...., and you can access them like echo $var4
foreach(range(0, 19) as $index)
{
$var = 'var' . $index;
$$var = $_SESSION[$var] = $_POST[$var];
}
With array $vars, and access them with echo $vars[4]
foreach(range(0, 19) as $index)
{
$var = 'var' . $index;
$vars[$var] = $_SESSION[$var] = $_POST[$var];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With