PHP Introduction to PHP Echo and print Tutorial


 

PHP Introduction to PHP Echo and print Tutorial

Do you know the difference between the common echo() and print() functions? Also you will find here a basic description of variable functions in PHP.

Do you know the difference between the common echo() and print() functions? Also you will find here a basic description of variable functions in PHP.
Ok, this is a basic tutorial to help people just getting started with PHP. In this tutorial I will show you how to output to the webpage. We will use two forms of outputting: print() and echo().


First things first: all newcomers to PHP will be happy to know that PHP code can be written or added directly to your HTML!! All you have to do is put it between the <?php and ?> tags.

     <?php
          php stuff
     ?>

Ok, now that said, let's go to what this tutorial was written for.
The first outputting function I will show you is print().
This is very easy to use, and in fact, the parentheses are not even necessary. The basic structure of print() is:

     <?php
          print("This is outputted to the webpage");
          print "so is this!";
     ?>

You can also declare variables and then output them using the print function:

     <?php
          $hello = "hello"
          print("$hello");     //this print the hello variable
          print "$hello";
     ?>

That's really all there is to it. One thing is that it cannot be used in a variable function, which I'll explain in a few minutes.

The next method of outputting to a webpage is the echo() function. It is used the same way as print().

     <?php
          $kool = "this is kool";
          echo ("$kool prints \"kool\"");
          echo "this does too!";
          echo("hello");
          echo "this prints \"hello\" too!";
     ?>

What's the difference between the two ? Well, one difference is that echo() can take multiple expressions:

     <?php
          echo "The first", "the second";
     ?>

Print cannot take multiple expressions. That is the main distinct difference!

So there, you now have 2 ways of outputting text or variables to the webpage, but what about that variable function you ask ? Well, variables functions are things that don't work with echo() and print(). It basically means that if you were to put the name of a function inside a statement, it would try to execute the function.
It is a very confusing concept, even for me, so visit the php manual on variable funtions for more info. Here is some example code that may help you understand variable functions:

<?php function foo()
{
    echo "In foo()\n";
}

function bar($arg = '')
{
    echo "In bar(); argument was '$arg'.\n";
}

$func = 'foo';
$func();
$func = 'bar';
$func('test');
?>


In the code above there are two simple functions are declared. Then their names are assigned to the variable and both functions are executed using this variable.

Ads