Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

arrays and foreach loops to work with input vars more efficiently

Tags:

variables

php

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?

like image 875
ejackd Avatar asked Apr 15 '17 11:04

ejackd


People also ask

Are forEach loops more efficient than for loops?

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.

Is forEach more efficient than for?

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.

Which is faster for loop or foreach loop?

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.


1 Answers

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];
}
like image 200
LF00 Avatar answered Sep 19 '22 13:09

LF00