Can you assign multiple variables at once in PHP like you can with Java?

前端 未结 5 460
伪装坚强ぢ
伪装坚强ぢ 2021-02-03 17:13

I want to create 5 variables of type array all at once. Is this possible? In Java I know you can, but can\'t find anything about PHP. I\'d like to do something like this:

<
相关标签:
5条回答
  • 2021-02-03 17:23

    Yes, you can.

    $a = $b = $c = $d = array();
    
    0 讨论(0)
  • 2021-02-03 17:24

    Since PHP 7.1 you can use square bracket syntax:

    [$var1, $var2, $var3, $var4, $var5] = array(1, 2, 3, 4, 5);
    

    [1] https://wiki.php.net/rfc/short_list_syntax
    [2] https://secure.php.net/manual/de/migration71.new-features.php#migration71.new-features.symmetric-array-destructuring

    0 讨论(0)
  • 2021-02-03 17:34
    $c = $b = $a;
    

    is equivalent to

    $b = $a;
    $c = $b;
    

    therefore:

    $var1 = $var2 = $var3 = $var4=  $var5 = array();
    
    0 讨论(0)
  • 2021-02-03 17:38

    I prefer to use the list function for this task. This is not really a function but a language construct, used to assign a list of variables in one operation.

    list( $var1, $var2, $var3 ) = array('coffee', 'brown', 'caffeine');

    For more information see the documentation.

    0 讨论(0)
  • 2021-02-03 17:46
    $var1 = $var2 = $var3 = $var4=  $var5 = array();
    
    0 讨论(0)
提交回复
热议问题