使用 switch 语句创建/添加数组
出于可读性和性能原因,我想使用 switch 语句而不是 if 语句
构建一个数组。
考虑下面的 if 语句:
$size = 2;
$array = array();
if($size >= 1) { array_push($array,'one','foo'); }
if($size >= 2) { array_push($array,'two','bar','barista'); }
if($size >= 3) { array_push($array,'three','zoo','fool','cool','moo'); }
它基本上从 1
计数到 $size
,使用 switch 语句可能会更具可读性,而且很可能会更快...... 但是你如何构建它?
$step = 2;
$array = array();
switch($step)
{
case ($step>1): array_push($array,'one','foo');
case ($step>2): array_push($array,'two','bar','barista');
case ($step>3): array_push($array,'three','zoo','fool','cool','moo');
}
我尝试省略break
,但它不起作用 - 正如手册所述:
在 switch 语句中,条件仅计算一次[...]。 PHP 继续执行语句直到切换结束 块,或者第一次看到break语句。
无论如何,有人知道如何使用 switch
语句构建这样的数组吗?
For readability and perfomance reasons, I'd like to build up an array with a switch statement instead of if-statements
.
Consider the following if-statement:
$size = 2;
$array = array();
if($size >= 1) { array_push($array,'one','foo'); }
if($size >= 2) { array_push($array,'two','bar','barista'); }
if($size >= 3) { array_push($array,'three','zoo','fool','cool','moo'); }
It basically counts up from 1
to $size
, it might be more readable and most likely a lot faster with a switch-statment...but how do you construct that ??
$step = 2;
$array = array();
switch($step)
{
case ($step>1): array_push($array,'one','foo');
case ($step>2): array_push($array,'two','bar','barista');
case ($step>3): array_push($array,'three','zoo','fool','cool','moo');
}
I tried leaving out the break
, which didn't work - as the manual says:
In a switch statement, the condition is evaluated only once[...].
PHP continues to execute the statements until the end of the switch
block, or the first time it sees a break statement.
Anyway, anyone got an idea how to build up such an array with a switch
-statement ??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当然,使用基于进一步的评论和后续编辑可以更轻松地实现您想要的效果
,例如:
然后展平 $array
Surely what you want can be achieved much more easily using
Based on further coments and subsequent edits, something like:
and then flatten $array
好吧, switch 语句看起来像:
编辑:上面的方法不起作用 - 让我看一下。
但在这个例子中,你可以这样做:
Well, a switch statement would look like:
edit: the above doesn't work - let me take a look.
but in this example, you could just do:
因此,如果
$step
为 2,则得到:...如果为 4,则得到:
So if
$step
is 2, you get:...and if it is 4, you get: