英文:
Convert this nested if to reduce dimensions as I am expecting to add more strings in the future
问题
这是我的代码。我不能发布实际的代码,但你只需要看到其中的3个字符串,我就会得到一个疯狂的维度。我该如何编写代码,以便能够包含超过10个值?
$x = 'a';
$y = 'b';
$z = 'c';
if ($x){
if($y){
if($z){
return $x.$y.$z;
}
return $x.$y;
}
return $x;
}
if($y){
if($z){
return $y.$z;
}
return $y;
}
if($z){
return $z;
}
return "";
英文:
This is my code. I cant post actual code but you can see only at 3 strings im ending up with crazy dimension. How can i write this in a way that is conducive to including more than say 10 values?
$x = 'a';
$y = 'b';
$z = 'c';
if ($x){
if($y){
if($z){
return $x.$y.$z;
}
return $x.$y;
}
return $x;
}
if($y){
if($z){
return $y.$z;
}
return $y;
}
if($z){
return $z;
}
return "";
</details>
# 答案1
**得分**: 1
为了简化嵌套的if语句,你可以根据它们的真值来连接字符串,像这样:
```php
$x = 'a';
$y = 'b';
$z = 'c';
$result = '';
if ($x) $result .= $x;
if ($y) $result .= $y;
if ($z) $result .= $z;
return $result;
对于未来的字符串,只需添加:
if ($newVariable) $result .= $newVariable;
英文:
To simplify your nested ifs, you can concatenate strings based on their truthy value like this:
$x = 'a';
$y = 'b';
$z = 'c';
$result = '';
if ($x) $result .= $x;
if ($y) $result .= $y;
if ($z) $result .= $z;
return $result;
For future strings, just add:
if ($newVariable) $result .= $newVariable;
答案2
得分: 1
这些字符串必须存储在单独的变量中吗?如果你可以将它们存储在一个数组中,你可以使用implode()
函数来连接它们。
例如:
$strs = [];
$strs[] = 'a';
$strs[] = 'b';
$strs[] = 'c';
return implode('', $strs); // abc
英文:
Do these strings have to be stored in separate variables? if you can store them in an array you can use implode()
to concatenate them.
E.g.
$strs = [];
$strs[] = 'a';
$strs[] = 'b';
$strs[] = 'c';
return implode('',$strs); // abc
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论