Boolean with PHP

Dup Some Basic PHP Questions

Hello,

I have a bunch of tinyint fields in a mysql database that I need to show using PHP. At the moment I am doing something like this:

if ($row['PAYPAL_ACCEPT'] == "1"){

$paypal = "Yes";

else

$paypal = "No";

}

      

For each field, which is tedious and seems like there must be a better way than using an if clause for each field. If so, what is it?

0


source to share


5 answers


Building on what has already been suggested:

// $columns = string array of column names
// $columns = array('PAYPAL_ACCEPT' ... );
foreach($columns as $column) {
  $$column = $row[$column] ? 'YES' : 'NO';
}

      



then you can access the variables using the column names as the variable names:

print $PAYPAL_ACCEPT;

      

+1


source


Try it if you like:



$paypal = $row['PAYPAL_ACCEPT'] ? 'YES' : 'NO';

      

+3


source


Something like

$paypal = ($row['PAYPAL_ACCEPT'] ? "Yes" : "No");

      

may be?

+2


source


You could write it shorter like:

$paypal = ($row['PAYPAL_ACCEPT']?'Yes':'No');

      

0


source


or you can use not tinyint but an enum with the values ​​"Yes" and "No", then a simple output field

$paypal = $row['PAYPAL_ACCEPT'];

      

0


source







All Articles