2.3. Sending Data to the Browser as Output

To see the data that you're processing, you need a way to send it as output. This enables you to display the contents of a variable in the browser to your users.

There are several ways to send output, but the most common methods are the commands echo(), print(), printf(), and sprintf(). There are differences in how you use each of these, but the result is the same: something is output for display in the browser.

2.3.1. The Different Output Commands

It's important to have a solid understanding of your options when sending output to the browser, so I'll go over the different statements available, how they work, and what special properties are associated with each.

NOTE

Whenever I introduce a language construct or function in the course of this book, I'll begin by walking you through the prototype, or breakdown, of the function's name, accepted arguments, and a return value defined by its datatype. Don't worry if you're not sure what that means yet because I'll cover all this information fully in the course of this chapter.

2.3.1.1. The print() Statement

The print() statement is the most straightforward method of generating output. Its prototype looks like this:

int print   ( string $arg   )

This means that print() accepts one argument, which is a string to be output to the browser, and returns an integerprint() always returns 1.

You can use print() by placing this code in test.php:

<?php
    print("Some text.");
?>

This code produces the following output if you reload test.php.

Some text.

2.3.1.2. The echo() Statement

The most common method of generating output is probably the echo() statement. It differs slightly from print() in that it can accept multiple arguments. Consider this prototype:

void echo  ( string $arg1  [, string $...  ] )

The echo() statement accepts one or more arguments, separated by commas, and outputs all of the arguments to the browser in succession. Unlike print(), echo() does not return a value—the void keyword in the prototype tells it not to.

Because echo() is also a language construct, the parentheses are optional and generally omitted. Add the following code to test.php:

<?php echo "Hello ", "world!"; ?>

The preceding snippet produces this output:

Hello world!

Your two strings are added together as arguments to the echo() statement, producing one string that ends up being passed to the browser. The same approach works for variables:

<?php
    $foo = "Hello ";
    $bar = "world!";
    echo $foo, $bar;
?>

This produces the same output as above:

Hello world!

NOTE

Because print() is a language construct and not a function, you can use it without parentheses (i.e., <?php echo 'Some text'; ?>); the clarity achieved with this syntax makes it the preferred approach for many developers. Benchmarks using echo() with arguments have generally proved slightly faster than any other method of outputting data to the browser, so I'll use this approach throughout the rest of this book.

2.3.1.3. The printf() Statement

The next statement, printf(), gives you more fine-grained control over your output, allowing you to define the format of data that will be sent to the browser. You can think of this statement as meaning "print formatted." This is especially useful when you're dealing with numbers, which I'll cover in a moment. First, take a look at the prototype for printf():

int printf  ( string $format  [, mixed $args  [, mixed $...  ]] )

NOTE

When a function accepts a mixed type, it means that the function can accept several argument types. Generally, all datatypes except arrays and objects are acceptable. Also, arguments in square brackets in a function prototype are optional.

At this point, you can pass a formatting string to printf() along with other arguments that will fit into the format. This is a great way to verify that the data you are passing is of the proper type for the task at hand. Try the following code in test.php:

<?php
    printf("PHP is %s!", "awesome");
?>

This snippet produces the following output:

PHP is awesome!

In the preceding code snippet, you created a formatting string ("PHP is %s!") with a conversion specification, which starts with a percentage sign (%) and is followed by a series of specifiers. In this example, you assigned a type specifier string, which tells the function what datatype the argument to expect.

The most practical use of printf() is with floating point numbers, such as dollar amounts. Consider the following code using echo():

<?php
    $amt1 = 2.55;
    $amt2 = 3.55;
    $total = $amt1 + $amt2;

    echo 'The total cost is $', $total;
?>

You might expect to see this sentence when you run your code:

The total cost is $6.10.

However, what you see when you run the code is this:

The total cost is $6.1

For obvious reasons, this isn't what you want to happen if you're trying to display a price. Fortunately, this is a case where printf() comes in handy; simply add the following code to test.php:

<?php
    $amt1 = 2.55;
    $amt2 = 3.55;
    $total = $amt1 + $amt2;

    printf('The total cost is $%.2f', $total);
?>

Saving and reloading produces the desired result:

The total cost is $6.10

The reason you get the properly formatted number in the latter case is that you've specified the type as a floating point number and told the printf() statement to return a decimal out to two places using your formatting string (%.2f). No matter what you pass as the argument, the output will be a floating point value with a decimal out to two places.

For example, you might try to placing a string into your printf() statement to see what happens. In test.php, try running the following code:

<?php printf('The total cost is $%.2f', 'string'), ?>

When you save and reload, you see the following output:

The total cost is $0.00

This happens because PHP tries to parse, or process, the string called string for a value of some sort; when it doesn't find one, it evaluates to zero, and the value is taken out to two decimal places by the formatting requirements.

Some of the more common datatype specifiers supported by printf() include:

  • %s: Treats the argument as and outputs a string

  • %d: Treats the argument as an integer and outputs a signed decimal

  • %f: Treats the argument as an integer and outputs a floating point number

NOTE

printf() supports a wide variety of datatypes, such as scientific notation, ASCII values, and octal numbers. You can learn more about this by visiting the PHP manual at http://www.php.net/manual/en/ and search for sprintf(). (printf() and sprintf() are very similar, so the manual only goes over type specifiers in the sprintf() entry).

2.3.1.4. The sprintf() Statement

The sprintf() statement works in the same way as the printf() statement: you provide a format with type specifiers and a set of arguments to be inserted into your formatting string. The only difference is that while printf() outputs directly to the browser, sprintf() returns a string.

Now is a good point to look at the prototype:

string sprintf  ( string $format  [, mixed $args  [, mixed $...  ]] )

The only difference you see between sprintf() and printf() is the "string" preceding the statement. The word preceding a function tells you what type of value a function will return.

The benefit of using sprintf() in our scripts is that you're able to format only select sections of data, which saves you from having to format the entire output.

For example, try placing the following code in your test.php file:

<?php
    $gpa1 = sprintf("%.1f", 4);
    $gpa2 = sprintf("%.1f", 3.7);
    echo 'Kelly had a ', $gpa1, ' GPA, and Tom had a ', $gpa2;
?>

When you save and reload, the output reads like this:

Kelly had a 4.0 GPA, and Tom had a 3.7

You were able to force the numbers to conform to a format necessary for them to make sense, but you weren't required to pass the entire string as a formatting string. However, if you want to format multiple variables in one call to sprintf() or printf(), you can do so easily with the following bit of code:

<?php
    printf('Kelly got a %.1f GPA, and Tom got a $.1f.', 4, 3.7);
?>

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.245.167