tags:

views:

119

answers:

5

Dup of http://stackoverflow.com/questions/330709/some-basic-php-questions#330829

Hello,

I have a heap of tinyint fields in a mysql database I need to show with 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 should be a better way, than using an if clause for each field. If there is, what is it?

+3  A: 

Try if you want:

$paypal = $row['PAYPAL_ACCEPT'] ? 'YES' : 'NO';
lpfavreau
This is called a Ternary Operator by the way: http://us3.php.net/language.operators.comparison.
lpfavreau
+2  A: 

Something like

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

maybe?

adam
+1  A: 

You could write it shorter like:

$paypal = ($row['PAYPAL_ACCEPT']?'Yes':'No');
Tader
+1  A: 

or you can use not tinyint but enum with values 'Yes' and 'No', then simple output field

$paypal = $row['PAYPAL_ACCEPT'];
Irmantas
+1  A: 

Building on what's 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 variables using the column names as variable names:

print $PAYPAL_ACCEPT;
chriscena
Would this matter that it included columns that were not booleans?
Joshxtothe4
That depends on what you mean by not booleans, as you can convert all kinds of data to booleans in PHP. If you want all the variables to contain either YES or NO, the you can use this. Again, I'm not sure what you mean.
chriscena