PHP variable variables

前端 未结 6 1140
别跟我提以往
别跟我提以往 2020-11-29 13:24

I want to store courseworks marks of n courseworks into n variables, such as cw1 and cw2 etc. Using variable variables how can I come with cw1, cw2 etc.

How can I d

相关标签:
6条回答
  • 2020-11-29 13:37

    You should really use an array, as Gumbo wrote:

    $cw = array();
    
    for($i = 0; $i < $n; ++$i) {
        $cw[] = $something;
    }
    

    However, a solution to your problem:

    for($i = 0; $i < $n; ++$i) {
        $tmp = 'cw' . $i;
        $$tmp = $something;
    }
    
    0 讨论(0)
  • 2020-11-29 13:38

    Not entirely sure I understand the question, but you can do something like this:

    $VarName = 'cw1';
    
    $$Varname = 'Mark Value';
    

    If you have a large number of these, you may be better off using an array for them, with indexes based on the coursework.

    ie:

    $a = array();
    $a['cw2'] = cw2value;
    // etc.
    
    0 讨论(0)
  • 2020-11-29 13:46

    Variable variables work in this way

    $var = "foo";
    $$var = "bar";
    
    echo $foo; // bar
    

    But i do not recommend doing this, since what if the value of $var changes, then you can no longer print out the 3rd line in this code.

    If you could elaborate more on what you want to do i think we could help you more.

    0 讨论(0)
  • 2020-11-29 13:48

    Use an array instead:

    An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible...

    0 讨论(0)
  • 2020-11-29 13:48
    <?php
    

    //You can even add more Dollar Signs

    $Bar = "a";
    $Foo = "Bar";
    $World = "Foo";
    $Hello = "World";
    $a = "Hello";
    
    $a; //Returns Hello
    $$a; //Returns World
    $$$a; //Returns Foo
    $$$$a; //Returns Bar
    $$$$$a; //Returns a
    
    $$$$$$a; //Returns Hello
    $$$$$$$a; //Returns World
    

    //... and so on ...//

    ?>
    
    0 讨论(0)
  • 2020-11-29 13:49
    php > for ($i=0; $i<5; $i++)
             { ${"thing{$i}"} = $i; }
    php > echo $thing1;
    1
    php > echo $thing2;
    2
    php > echo $thing3;
    3
    

    Note that we're using the dollar sign around curly braces around a string.

    0 讨论(0)
提交回复
热议问题