Displaying Output using PHP
There are number of functions and language constructs in PHP to send output to the screen. Lets see few of them.
echo is a language construct and is not a function so never use parenthesis in front of it. We will discuss functions later.
Any number of parameters can be passed inside echo separated by commas.
echo outputs all the parameters as a string but returns nothing. No value is returned by echo. Thats why its return type is void.
Syntax for using echo:
void echo $arg1 [,$arg2... ]
Now copy the below code and paste it in a notepad file, save it and execute it to see what it shows as output.
<?php echo "Hello"; echo "<br />"; echo "World"; echo "<br />"; echo "All", " in ", "one ", "line."; ?>
echo can be used with HTML tags. Check how I used <br /> tags.
print is also a language construct similar to echo but with few differences.
Only single argument can be passed inside print which it display as string.
Unlike echo, print always returns 1. Hence its return type is int. We will talk more about return type later.
Syntax for using print:
int print $arg
Try the code below to see how it works.
print "Hello"; print "<br />"; print "World";
Try to pass more than one parameters inside print to see what error message it shows.
printf is a function used to output a formatted string.
If you are familiar with the language C, then you will find it close to C language's printing style.
Syntax for using printf:
int printf ( string $format [, mixed $args [, mixed $... ]] )
Run the code below:
printf("There are %d days in a week.", 7); printf("<br />"); printf("There are %d words in the name %s", 5, "Alice");
Notice how %d is replaced with number '7' in first instruction.
In the second instruction %d is replaced with '5' and %s with "Alice". %d and %s are known as format specifiers. %s is for strings, %d is for integers, %f for float types. We will discuss all this in details later after completing data types and variables.