vendredi 14 septembre 2018

PHP - Make nested if statement output shorter

I often end up with something like below:

<?php
foreach($items as $item) {
  if($item['key']) {
    echo 'Alright';

    if($item['value']) {
      echo 'Inside';
    } else {
      $output[] = [
        $item['data1'],
        $item['data2'],
      ];
    }
  } else {
    $output[] = [
      $item['data1'],
      $item['data2'],
    ];
  }
}

print_r($output);

As you can see I use nested if statements. What nags me is that I have the same output in both else. I would prefer keep things DRY.

So, if I'm in an else statement anywhere within the foreach, I want to output the same results.

Aucun commentaire:

Enregistrer un commentaire