Convert this nested if to reduce dimensions as I am expecting to add more strings in the future

huangapple go评论50阅读模式
英文:

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 = &#39;a&#39;;
$y = &#39;b&#39;;
$z = &#39;c&#39;;

$result = &#39;&#39;;

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[] = &#39;a&#39;;
$strs[] = &#39;b&#39;;
$strs[] = &#39;c&#39;;

return implode(&#39;&#39;,$strs); // abc

</details>



huangapple
  • 本文由 发表于 2023年8月9日 06:24:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/76863527.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定