Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


PHP concepts for beginners

Abel Lifaefi Mbula

There are many concepts in PHP that create confusion for beginners. Some of the main ones are as follows:

  1. echo
  2. print
  3. include
  4. require

The first two words display strings, and the last two call a file inside another one.

Let’s get started.

1. echo vs. print

We use echo and print to output strings. The syntax looks like this:

// echo
echo 'This is a string';

// print
print 'This is a string';

With echo, we can have more than one parameter. The print command only supports one parameter and returns 1. The return value for echo is null.



echo "<h1>Educative, Inc</h1>";
echo "<p>This is Educative. The best place to learn!</p>";
echo '"echo"', " with multiple ", "parameters\n";

$name = "Patience Kavira";
print "Your name is $name";

// Non-string values are coerced to string
print 5 * 5;
The echo and print command

We can learn more about echo and print here.

2. include vs. require

We use both include and require to call a PHP script inside another one. Imagine we build a website that has a common code like header and footer. What do we do to work with these code snippets on different pages of our site?

If we want to write clean code and follow the DRY principle, we'll need to put common code in a single file and call it where needed.

Let's see another example. In most cases, config or sensitive information, like the database, is kept in a separate file. Therefore, we'll need to call this file every time we want to access the database.

Let's look at the syntax and the difference between them:

require "path/to/file";
// or
include "path/to/file";

The only difference between require and include is when the called file is missing. In such cases, require produces a fatal error and stops the script while include continues running but produces a warning. Hence, as a general rule, it is preferable to use require for sensitive files and include for others.



 * @author Abel L Mbula
include "includes/header.php";

echo "<h1>Contact</h1>";
echo "<p></p>";

include "/includes/footer.php";


We've learned that echo and print can both display strings but print does not have a return value and echo can accept multiple parameters. On the other hand, we also learned that to call a file inside another file, we use include or require. The difference between them is that include does not throw a fatal error when the called file is missing, while require does.



View all Courses

Keep Exploring