PHP file

  • PHP files have extension “.php”
  • They can contain text, HTML, CSS, JavaScript, and PHP code
  • PHP code is executed on the server, and the result is returned to the browser as plain HTML
echo "Hi there.\n";
$answer = 6 * 7;
echo "The answer is $answer";
<p>Another paragraph.</p>


To install PHP, check official documentation.


A PHP script can be placed anywhere in the document. It starts with :

// PHP code

In PHP, keywords (echo, if, else, etc), classes, and functions are not case-sensitive.

ECHO "Hello<br>";
echo "Hello<br>";
EcHo "Hello<br>";

Comments in PHP

  • Syntax for single-line comment:
// This is a single-line comment

# This is also a single-line comment
  • Syntax for multiple-line comments:
This is a


Variables start with a dollar sign ($) followed by the name of the variable.

A variable name

  • must start with a letter or the underscore character
  • can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
  • is case-sensitive ($name and $NAME are two different variables)
$abc = 12;

Variable scopes

A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function:

$x = 5; // global scope

function count() {
  // using x inside this function will generate an error
  echo "<p>Variable x is: $x</p>";

echo "<p>Variable x is: $x</p>";

A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function:

function count() {
  $x = 5; // local scope
  echo "<p>Variable x is: $x</p>";

// using x outside the function will generate an error
echo "<p>Variable x is: $x</p>";


  • String literals can use single quotes or double quotes.
  • The backslash () is used as an “escape” character.
  • Strings can span multiple lines - the newline is part of the string.
  • In double-quoted strings, variable values are expanded.
  • \n doesn’t work inside of a single-quoted string
  • Concatenation is the “.” not “+”
echo "this is a simple string\n";
echo "You can also have embedded newlines in
strings this way as it is
okay to do";

echo "This will expand: \na newline";
// Outputs: This will expand:
// a newline

$expand = 12;
echo "Variables do $expand\n";
// Outputs: Variables do 12


There are two ways to get output in PHP: echo and print.

The differences:

  • echo has no return value while print has a return value of 1
  • echo can take multiple parameters while print can take one argument


echo is a language construct. It can be treated like a function with one parameter.

Without parentheses, it accepts multiple parameters.

echo "Hello world!";


print is a function. It only has one parameter, but parentheses are optional so it can look like a language construct.

print "Hello world!";