Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Introduction to PHP - Basic Syntax and Structure

What is PHP?

PHP is a popular general-purpose scripting language that is especially suited to web development. It was originally created by Danish-Canadian programmer Rasmus Lerdorf in 1994. The PHP reference implementation is now produced by The PHP Group.

Basic Syntax

PHP scripts are executed on the server. The basic syntax for PHP includes a combination of HTML and PHP code. PHP code is enclosed in special start and end processing instructions: <?php ... ?>.

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

PHP Tags

There are four different pairs of tags that can be used in PHP:

  • Standard tags: <?php ... ?>
  • Short tags: <? ... ?> (must be enabled in php.ini)
  • ASP-style tags: <% ... %> (deprecated)
  • HTML script tags: <script language="php"> ... </script>

Comments

Comments in PHP are similar to those in C, C++, and Unix shell scripts. PHP supports three different ways of commenting:

  • Single-line comments can be written using // or #
  • Multi-line comments can be written using /* ... */
<?php
// This is a single-line comment

# This is also a single-line comment

/*
This is a multi-line comment
that spans multiple lines
*/
?>

Variables

Variables in PHP are represented by a dollar sign followed by the name of the variable. Variable names are case-sensitive.

<?php
$txt = "Hello, World!";
$num = 123;
?>

Echo and Print

The echo and print statements are used to output data to the screen. Both can be used with or without parentheses.

<?php
echo "This is an echo statement.";
echo("This is also an echo statement.");

print "This is a print statement.";
print("This is also a print statement.");
?>

Data Types

PHP supports several data types:

  • String
  • Integer
  • Float (floating point numbers - also called double)
  • Boolean
  • Array
  • Object
  • NULL
  • Resource

Operators

PHP supports a wide range of operators:

  • Arithmetic operators: +, -, *, /, %
  • Assignment operators: =, +=, -=, *=, /=, %=
  • Comparison operators: ==, ===, !=, <>, <, <=, >, >=
  • Logical operators: &&, ||, !

Control Structures

PHP supports various control structures:

  • Conditional statements: if, else, elseif, switch
  • Looping statements: while, do-while, for, foreach
<?php
// if-else statement
if ($num > 0) {
    echo "The number is positive.";
} else {
    echo "The number is not positive.";
}

// for loop
for ($i = 0; $i < 10; $i++) {
    echo $i;
}
?>

Functions

Functions in PHP are blocks of code that perform specific tasks. They are defined using the function keyword.

<?php
function sayHello() {
    echo "Hello, World!";
}

sayHello(); // calling the function
?>