Codeskill

Learn to code, step by step

PHP Syntax: The Basics of Writing PHP Scripts

The basic rules of PHP syntax matters once your pages get past the basics. How scripts are structured and the building blocks you will use in every file.

What is PHP syntax?

Syntax is the set of rules for writing code the computer can understand. PHP borrows from C, Java, and Perl, with a few features of its own.

Basic structure

A PHP script starts with <?php and ends with ?>. Everything between those tags is PHP code:

<?php
// PHP code goes here
?>

Echo and print statements

Use echo or print to output text. They do much the same job, with small differences under the hood:

<?php
echo "Hello, world!";
print "Hello again, world!";
?>

Variables

Variables store data. In PHP, every variable name starts with a dollar sign $:

<?php
$text = "PHP is fun!";
$number = 10;
?>

Data types

PHP supports several data types for different kinds of information:

  • Strings: Text values, e.g. "Hello, PHP!".
  • Integers: Whole numbers, e.g. 42.
  • Floats (or doubles): Decimal numbers, e.g. 3.14.
  • Booleans: Either TRUE or FALSE.
  • Arrays: Multiple values in one variable.
  • Objects: Instances of classes, used in object-oriented programming.
  • NULL: A variable with no value.

Quick example:

<?php
$string = "This is a string";
$integer = 100;
$float = 10.5;
$boolean = true; // or false
?>

Strings and concatenation

Join strings together with the . operator:

<?php
$part1 = "PHP is ";
$part2 = "awesome!";
$sentence = $part1 . $part2;
echo $sentence; // Outputs: PHP is awesome!
?>

Control structures: if, else, and switch

Control structures let your code make decisions. if, else, and switch are the main ones:

<?php
$number = 10;

if ($number > 10) {
    echo "Number is greater than 10.";
} elseif ($number == 10) {
    echo "Number is exactly 10.";
} else {
    echo "Number is less than 10.";
}
?>

Arrays

Arrays hold multiple values. They can be indexed (numbered) or associative (key-value pairs):

<?php
$colors = array("Red", "Green", "Blue");
echo $colors[0]; // Outputs: Red
?>

Loops: for, while, and foreach

Loops run the same block of code more than once:

  • For loop: Repeats a set number of times.
  • While loop: Repeats while a condition is true.
  • Foreach loop: Loops through an array.
<?php
for ($i = 0; $i < 3; $i++) {
    echo $i . " ";
}
?>

Functions

A function is a block of code you define once and call whenever you need it:

<?php
function greet() {
    echo "Hello, PHP!";
}
greet(); // Call the function
?>

Commenting your code

Comments are ignored by PHP but help anyone reading your code. Use // for single lines and /* ... */ for blocks:

<?php
// This is a single-line comment
/* This is a
multi-line comment */
?>

That covers the basics of PHP syntax. Try writing a few small scripts with what you have learned here – the next pages go into more detail on each topic.

PreviousGetting Started with PHP: Setting Up Your Environment