同时初始化多个PHP变量

时间:2012-03-11 02:00:44

标签: php

如何在不使用数组的情况下同时初始化多个值为零的PHP变量?我希望编写的代码基本上等同于以下内容:

$first = 0;
$second = 0;
$third = 0;
$fourth = 0;

3 个答案:

答案 0 :(得分:82)

$first = $second = $third = $fourth = 0;

答案 1 :(得分:16)

虽然在for循环中使用逗号运算符初始化多个变量是可行的,但如下所示:

<?php
for ($a=0,$b=0,$c=0,$d=0;;) {
    break;
}
var_dump($a,$b,$c,$d);

(参见演示here

list 构造提供了一种更有效的方式来执行多个变量赋值,如以下示例所示:

<?php

list( $first, $second, $third, $fourth ) = array( 0, 0, 0, 0 );
var_dump($first, $second, $third, $fourth );

请参阅演示here

有人可能希望重新考虑避免使用数组来实现多个初始化变量。使用PHP7.1 +,如果使用短数组语法可用的array destructuring,可以编写更简单,更健壮的代码,如下所示:

<?php

[$first, $second, $third, $fourth ] = [0, 0, 0, 0];
var_dump($first, $second, $third, $fourth );

请参阅演示here

如果需要确定先前未设置的初始化变量,请参阅此相关discussion,尤其是此response

答案 2 :(得分:1)

  

如果要初始化多个数组变量,请使用

SELECT 
  UID, 
  CASE STATES 
    WHEN 1 THEN 'PATCHED'
    WHEN 2 THEN 'NOTPATCHED'
    WHEN 3 THEN 'NOTAPPLICABLE'
  END AS States_new
FROM COMPUTERS
  

如果要初始化多个常规变量,请使用

# Initialize multiple array variables with Empty values
$array_1 = $array_2 = $array_3 = array();

# Initialize multiple array variables with Some values in it
list( $array_1, $array_2, $array_3) = array('one','two','three');

# Print value of array variables
var_dump($array_1,$array_2,$array_3);

Output:
*******
string 'one' (length=3)
string 'two' (length=3)
string 'three' (length=5)