Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I clean up this if/else statement? (refactoring)

I know there must be a nicer way to do this, but whenever I search "&&" i don't get good enough results...

<?php
if (empty($row[ContactName]) && empty($row[ContactEmail]) && empty($row[ContactPhone]) && empty($row[Website])){
echo "Not Provided";
}
else{
...do stuff...
}
?>

Thanks!

like image 461
Joel Avatar asked Jul 18 '12 05:07

Joel


2 Answers

What is wrong with the original code?

<?php
if (empty($row[ContactName]) 
    && empty($row[ContactEmail]) 
    && empty($row[ContactPhone]) 
    && empty($row[Website]))
{
    echo "Not Provided";
} 
else{
 ...do stuff...
}
?>

Looks like fine code to me...

like image 114
Tommy Avatar answered Oct 17 '22 16:10

Tommy


<?php
$i=1;
$ar=array('ContactName','ContactEmail','ContactPhone','Website')

foreach($ar as $a)
  if (empty($row[$a]))
    {
     $i=0;
     break;                      //to make code fast
    }
  if($i)         //do stuff
  else echo 'not provided';
?>

or if you really want to make your code extra small then change your column name in database

From               To
ContactName        Col1
ContactEmail       Col2
ContactPhone       Col3
Website            Col4

and then do

 <?php
  $i=1;
  for($a=1;$a<5;$a++)
    if (empty($row['Col'.$a]))
    {
      $i=0;
      break;
    }
  if($i)//do stuff
  else echo 'Not Provided';
    ?>

However it is not good to rename column as it will make your db somewhat less understandable.

like image 29
bugwheels94 Avatar answered Oct 17 '22 14:10

bugwheels94