【问题标题】:PHP: what is the convinient way to store variables in array? [closed]PHP:将变量存储在数组中的便捷方法是什么? [关闭]
【发布时间】:2013-11-02 14:19:36
【问题描述】:

我知道可以这样做

test['array'][0] = 'A';
test['array'][1] = 'B';
test['array'][2] = 'C';
test['array'][3] = 'D';

有没有比上面的例子更简单或更好的方法将变量存储在数组中? ^_^

【问题讨论】:

  • 做一些谷歌或者有PHP手册,这是非常基本的,可以在手册中轻松获得。

标签: php arrays store


【解决方案1】:
$test['array']=['A','B','C','D'];

【讨论】:

  • +1 它比我的解决方案更好:)
  • 这甚至是有效的 PHP 吗?您应该使用方括号 (PHP 5.4+) 而不是花括号。
  • php 5.4+ is $test ['array'] = ['A', 'B'...我从没见过 { }
  • 这更好,但我喜欢粗鲁的答案,因为它适用于所有版本,但更简单
【解决方案2】:

默认方式(适用于所有 PHP 版本)

$test['array'] = array('A','B','C','D');

在 PHP 5.4 及更高版本中,您可以使用 JS 样式的数组声明

$test['array'] = ['A','B','C','D'];

【讨论】:

  • 这两个例子中哪个执行得更快?
  • 两者都是语言结构,所以应该没有速度差异
【解决方案3】:
test['array'][] = 'A';
test['array'][] = 'B';
test['array'][] = 'C';
test['array'][] = 'D';

甚至更简单:

test[] = 'A';
test[] = 'B';
test[] = 'C';
test[] = 'D';

【讨论】:

    【解决方案4】:

    $test['array'] = ['A', 'B', 'C', 'D'];

    array_push($test['array'], 'A', 'B', 'C', 'D');

    【讨论】:

      猜你喜欢
      • 2012-10-17
      • 1970-01-01
      • 1970-01-01
      • 2010-10-10
      • 1970-01-01
      • 1970-01-01
      • 2011-05-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多