skip to Main Content

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 "";

2

Answers


  1. 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;
    
    Login or Signup to reply.
  2. 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
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search