这个PHP逻辑控制结构如何重构呢?
我的直觉告诉我,下面的代码有一个更好的、也许是单行的重构:
if (isset($x))
{
if (isset($y))
{
$z = array_merge($x,$y);
}
else
{
$z = $x;
}
}
else
{
$z = $y;
}
如果我不担心警告错误,一个简单的 array_merge($x,$y) 就可以工作,但我想知道更好的方法来做到这一点。想法?
My gut tells me that there is a better, perhaps one-line refactor for the following code:
if (isset($x))
{
if (isset($y))
{
$z = array_merge($x,$y);
}
else
{
$z = $x;
}
}
else
{
$z = $y;
}
If I wasn't worried about warning errors, a simple array_merge($x,$y)
would work, but I'd like to know a better way to do this. Thoughts?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果
$x
和$y
未设置,这将返回一个空数组。如果只设置了一个,它将返回该数组。如果两者都设置了,它将返回在数组上运行array_merge()
的结果。这并不完全是您上面代码的行为,但我相信这是您想要的行为。 (我相信,在您的代码中,如果
$x
和$y
均未设置,则$z
将不是数组。)顺便说一句,此代码假设如果设置了
$x
和$y
,则它们是数组。如果情况并非如此,您应该对它们运行is_array()
以确认它们是数组,或者使用 类型杂耍,以确保在array_merge()
运行时它们是数组。This will return an empty array if
$x
and$y
are not set. If only one is set, it will return that array. If both are set, it will return the result ofarray_merge()
run on the arrays.That is not quite the behavior of your code above, but I believe it is the behavior you intended. (I believe, in your code, that
$z
will not be an array if both$x
and$y
are not set.)By the way, this code assumes that if
$x
and$y
are set, that they are arrays. If that is not the case, you should either runis_array()
on them to confirm they are arrays or use type juggling to make sure they are arrays whenarray_merge()
runs.