Home > Software design >  change if else Structure to a loop
change if else Structure to a loop

Time:02-24

I have the following ifelse structure which works fine for me. However, now I have to add some lines and I was wondering, if there is a way to change it to a loop, to reduce the lines of code.

if     ($class_number == 0) {$klassliste = array();}              
elseif ($class_number == 1) {$klassliste = array(1);}             
elseif ($class_number == 2) {$klassliste = array(1,2);}           
elseif ($class_number == 3) {$klassliste = array(1,2,3);}         
elseif ($class_number == 4) {$klassliste = array(1,2,3,4);}       
elseif ($class_number == 5) {$klassliste = array(1,2,3,4,5);}     
elseif ($class_number == 6) {$klassliste = array(1,2,3,4,5,6);}   
elseif ($class_number == 7) {$klassliste = array(1,2,3,4,5,6,7);} 

CodePudding user response:

Definitely you can.

Easy way, using PHP's range function:

$class_number = 7;
$klassliste = range(1, $class_number);

var_dump($klassliste);

Demo: https://3v4l.org/9tfVm


For completeness / explanation, an explicit way using a loop as you requested (but not really necessary because range will do it for you):

$klassliste = array();
$class_number = 7;

for ($i = 1; $i <= $class_number; $i  )
{
     $klassliste[] = $i;
}

var_dump($klassliste);

Demo: https://3v4l.org/NLaI4

CodePudding user response:

No need for an if...else, or a loop. Just use range():

$class_number = 5;
$klasslist = [];
if ($class_number) {
    $klasslist = range(1,$class_number);
    
}
print_r($klasslist);

See https://3v4l.org/ekIBM

CodePudding user response:

there are a few possibilities:

$klassliste = [];
for ($i = 0; $i < $class_number; $i  ) {
    $klassliste[] = $i   1;
}

or with a 1liner

$klassliste = $class_number === 0 ? [] : range(1, $class_number);

see https://3v4l.org/QhFpG

  • Related