Asked  7 Months ago    Answers:  8   Viewed   25 times

how do i create variable variables inside a for loop?

this is the loop:

for ( $counter = 1; $counter <= $aantalZitjesBestellen; $counter ++) {

}

inside this loop i would like to create a variable $seat for each time it passes but it has to incrementlike so. first time it passes it should be $seat1 = $_POST['seat'+$aantalZitjesBestellen], next time it passes: $seat2 = $_POST['seat'+$aantalZitjesBestellen] and so on.

so at the end it should be:

$seat1 = $_POST['seat1'];
$seat2 = $_POST['seat2'];

and so on.

so the variable and the content of the $_POST should be dynamic.

 Answers

36

Firstly, I would use an array for this unless I'm missing something. Having variables like $seat1, $seat2, etc tends to have far less utility and be far more cumbersome than using an array.

That being said, use this syntax:

for ( $counter = 1; $counter <= $aantalZitjesBestellen; $counter ++) {
  $key = 'seat' . $counter;
  $$key = $_POST[$key];
}

Lastly, PHP has an inbuilt function for extracting array keys into the symbol table: extract(). extract() has enormous potential security problems if you use it with unfiltered user input (eg $_POST) so use with caution.

Wednesday, March 31, 2021
 
Webroots
answered 7 Months ago
61
  • $hash('foo') is a variable function.
    $hash may contain a string with the function name, or an anonymous function.

    $hash = 'md5';
    
    // This means echo md5('foo');
    // Output: acbd18db4cc2f85cedef654fccc4a4d8
    echo $hash('foo');
    
  • $$foo is a variable variable.
    $foo may contain a string with the variable name.

    $foo = 'bar';
    $bar = 'baz';
    
    // This means echo $bar;
    // Output: baz
    echo $$foo;
    
  • $bar[$foo] is a variable array key.
    $foo may contain anything that can be used as an array key, like a numeric index or an associative name.

    $bar = array('first' => 'A', 'second' => 'B', 'third' => 'C');
    $foo = 'first';
    
    // This tells PHP to look for the value of key 'first'
    // Output: A
    echo $bar[$foo];
    

The PHP manual has an article on variable variables, and an article on anonymous functions (but I didn't show an example above for the latter).

Wednesday, March 31, 2021
 
clean_coding
answered 7 Months ago
35

Rasmus Lerdorf wrote a static analysis tool that can spot these so-called Uniform Variable Syntax issues, called Phan https://github.com/etsy/phan

Phan has the option -b, --backward-compatibility-checks to check for potential PHP 5 -> PHP 7 BC issues.

Wednesday, March 31, 2021
 
Easen
answered 7 Months ago
72

Because the manual says so:

Warning

Please note that variable variables cannot be used with PHP's Superglobal arrays within functions or class methods. The variable $this is also a special variable that cannot be referenced dynamically.

http://php.net/manual/en/language.variables.variable.php

It's simply "special". PHP is "special". Superglobals don't play by the same rules as regular variables to begin with. Someone forgot to or decided against making them compatible with variable variables in functions. Period.

Saturday, May 29, 2021
 
skrilled
answered 5 Months ago
94

This should do it just fine:

$newArray = array_map(function (array $item) {
    return $item[0]."some code".$item[1]."some code".$item[2]."some code";
}, $array);

var_dump($newArray);

I don't see where separate variables are needed at all.

If you just continuously number variables dynamically ($item1, $item2 etc.), you're trying to hold a dynamic number of elements. That's exactly what arrays are for: $items[0], $items[1] etc.

Saturday, May 29, 2021
 
Hilmi
answered 5 Months ago
83

tl;dr: Don't use eval!

There is no single solution for this. It is possible to access some global variables dynamically via window, but that doesn't work for variables local to a function. Global variables that do not become a property of window are variables defined with let and const, and classes.

There is almost always a better solution than using variable variables! Instead you should be looking at data structures and choose the right one for your problem.

If you have a fixed set of names, such as

// BAD - DON'T DO THIS!!!
var foo = 42;
var bar = 21;

var key = 'foo';
console.log(eval(key));

store the those name/values as properties of an object and use bracket notation to look them up dynamically:

// GOOD
var obj = {
  foo: 42,
  bar: 21,
};

var key = 'foo';
console.log(obj[key]);

In ES2015+ it's even easier to do this for existing variables using concise property notation:

// GOOD
var foo = 42;
var bar = 21;
var obj = {foo, bar};

var key = 'foo';
console.log(obj[key]);

If you have "consecutively" numbered variables, such as

// BAD - DON'T DO THIS!!!
var foo1 = 'foo';
var foo2 = 'bar';
var foo3 = 'baz';

var index = 1;
console.log(eval('foo' + index));

then you should be using an array instead and simply use the index to access the corresponding value:

// GOOD
var foos = ['foo', 'bar', 'baz'];
var index = 1;
console.log(foos[index - 1]);
Tuesday, June 1, 2021
 
scessor
answered 5 Months ago
13

Sometimes we need software that is extremely flexible and that we can parametrize. You have to prepare the whole thing, of course, but part of it just comes from user input, and we have no time to change the software just because the user needs a new input.

With variable variables and variable functions you can solve problems that would be much harder to solve without them.

Quick Example:

Without variable variables:

$comment = new stdClass(); // Create an object

$comment->name = sanitize_value($array['name']);
$comment->email = sanitize_values($array['email']);
$comment->url = sanitize_values($array['url']);
$comment->comment_text = sanitize_values($array['comment_text']);

With variable variables

$comment = new stdClass(); // Create a new object


foreach( $array as $key=>$val )
{
    $comment->$key = sanitize_values($val);
}
Thursday, July 29, 2021
 
Lance
answered 3 Months ago
36
var color = 'red';
window[color] = 'dark';
console.log(color, red);
Tuesday, August 31, 2021
 
Marcelo
answered 2 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :