MoonPoint Support Logo

 

Shop Amazon Warehouse Deals - Deep Discounts on Open-box and Used ProductsAmazon Warehouse Deals



Advanced Search
July
Sun Mon Tue Wed Thu Fri Sat
28
       
2012
Months
Jul


Sat, Jul 28, 2012 10:26 pm

Printing Boolean Values as Yes or No

If you have a PHP variable that is storing Boolean data, i.e. 0 for "false" or "no" and 1 for "true" or "yes", but want to display the value as "no" when a zero is stored in the variable and "yes" when a one is stored in the variable, you can print the value using the ternary operator, ?, which is described in the Ternary Operator section of the manual page Comparison Operators.

E.g., suppose I have an array named swinfo that has information on various software packages that has an array variable Free that has a 0 stored in it if the software is not free and a 1 stored in it if the software is free. If I have a software package that isn't free, if I just print the contents of the variable as in the first instance below, I get a zero, but by using ther ternary operator, i.e., the ?, I can specify that I want "yes" or "no" displayed, instead as for the second instance where it is displayed below.

      echo "<table>\n" .

      "<tr>\n" .
       "<td><b>Free:</b></td><td>" .
        $swinfo['Free'] . "</td>" .
       "</tr>\n" .

       "<tr>\n" .
       "<td><b>Free:</b></td><td>" .
        ($swinfo['Free'] ? 'yes' : 'no') . "</td>" .
       "</tr>\n" .

       "</table>\n";

For an instance where the software isn't free, I would see the following displayed:

Free:0
Free:no

References:

  1. Echo boolean field as yes/no or other values
    Stack Overflow
  2. Comparison Operators
    PHP: Hypertext Preprocessor

[/languages/php] permanent link

Sat, Jul 28, 2012 9:12 pm

Printing an array with print_r

The contents of an array can be printed in PHP using print_r. E.g., suppose that the information to be displayed is stored in a database in a table called tests that has student test scores with each student identified by a student id. The following PHP code could be used to fetch the test information for a student whose id is stored in the variable $num and then print the entire array named testinfo.

$result1 = mysql_query("SELECT * FROM tests WHERE ID = $num");
$testinfo = mysql_fetch_array($result1);
print_r ($testinfo);

References:

  1. Print_r () PHP Function
    By Angela Bradley
    About.com PHP/MySQL

[/languages/php] permanent link

Valid HTML 4.01 Transitional

Privacy Policy   Contact

Blosxom logo