A Beginner’s Guide to Essential PHP Syntax

Shafekul Abid
6 min readAug 24, 2023

--

Getting Started with PHP Syntax

Exploring the fundamental syntax of PHP

PHP is a versatile scripting language used for web development. Whether you're new to programming or transitioning from another language, understanding PHP's fundamental syntax is essential. In this guide, we'll explore the key syntax elements that form the foundation of PHP programming.

Table of Contents

1. Tags and Output
2. Variables and Data Types
3. Concatenation
4. Arithmetic Operators
5. Conditional Statements
6. Loops
7. Arrays
8. Functions
9. Superglobals
10. Include and Require

1. Tags and Output

PHP code is enclosed within `<?php` and `?>` tags. To display output, use the `echo` or `print` functions. For example, the code below displays the message "Hello, PHP!" on the webpage:

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

2. Variables and Data Types

Declare variables with the `$` symbol, followed by the variable name. PHP supports various data types like strings, integers, floats, and booleans. Here's how you can define and use variables:

$name = "John";          // String
$age = 25; // Integer
$price = 19.99; // Float
$is_active = true; // Boolean

3. Concatenation

Combine strings using the `.` operator. Here’s how concatenation works:

$name = "John";
$age = 30;

// Using concatenation to create a sentence
$sentence = "My name is " . $name . " and I am " . $age . " years old.";

echo $sentence; // Outputs: My name is John and I am 30 years old.

In this example, the `.` operator is used to concatenate the values of the variables `$name` and `$age` with the string "My name is" and "and I am", creating a sentence.

You can also directly concatenate strings within double-quoted strings:

$name = "Alice";

// Using variable interpolation for concatenation
$message = "Hello, $name! How are you today?";

echo $message; // Outputs: Hello, Alice! How are you today?

In this case, the variable `$name` is automatically interpolated within the double-quoted string, and the result is a concatenated message.

Remember that concatenation can also be used to build HTML content dynamically, create SQL queries, and more. It's a powerful technique for combining strings and values to create meaningful output or data structures.

4. Arithmetic Operators

Perform basic arithmetic operations with `+`, `-`, `*`, `/`, and `%`. The following code calculates the sum of two numbers:

$number1 = 5;
$number2 = 3;

$result = $number1 + $number2; // Adds the two numbers
echo $result;

5. Conditional Statements

Make decisions using `if`, `else if`, and `else` statements. This code checks if a person is an adult based on their age:

if ($age > 18) {
echo "You are an adult.";
} else {
echo "You are a minor.";
}

6. Loops

PHP supports different types of loops. Here are examples of `for`, `while`, and `foreach` loops:

// for loop
for ($i = 0; $i < 5; $i++) {
echo $i;
}

// while loop
$num = 0;
while ($num < 5) {
echo $num;
$num++;
}

// foreach loop
$colors = array("red", "green", "blue");
foreach ($colors as $color) {
echo $color;
}

7. Arrays

Create arrays to store multiple values. In this code, the array `$colors` holds different color names:,

$colors = array("red", "green", "blue");

Learn More about Arrays in my article PHP Advanced Syntax Elements.

8. Functions

Functions in PHP allow you to group a set of statements together and give them a name. This promotes code reusability and organization. Here’s how functions work


// Define a function
function greet($name) {
echo "Hello, $name!";
}

// Call the function
greet("Alice"); // Outputs: Hello, Alice!
greet("Bob"); // Outputs: Hello, Bob!

You can also have functions that return values:

function add($a, $b) {
return $a + $b;
}

$result = add(3, 5); // $result will be 8

In this case, the return statement is used to send a value back to the caller.

Functions can have default parameter values:

function greet($name = "Guest") {
echo "Hello, $name!";
}

greet(); // Outputs: Hello, Guest!
greet("Alice"); // Outputs: Hello, Alice!

You can use the global keyword to access global variables within a function:

$globalVar = "I'm global!";

function printGlobal() {
global $globalVar;
echo $globalVar;
}

printGlobal(); // Outputs: I'm global!

However, it’s generally recommended to pass variables as parameters to functions rather than relying on global variables.

Remember that functions in PHP can have access modifiers like public, protected, and private when used within classes, just like other class members.

9. Superglobals

Superglobals are special arrays in PHP that provide access to various types of data from different sources. Two commonly used superglobals are `$_GET` and `$_POST`, which are used to handle data from forms or URLs. Here’s how they work:

Using `$_GET` for URL Parameters:

Suppose you have a URL like this: `http://example.com/index.php?name=Alice&age=25`

You can access the values of `name` and `age` using the `$_GET` superglobal:

$name = $_GET['name']; // $name will be "Alice"
$age = $_GET['age']; // $age will be 25

This is commonly used for passing data via URLs, like when submitting data through links or from other web pages.

Using `$_POST` for Form Data:

When you submit a form using the HTTP POST method, the data is sent to the server and can be accessed using the `$_POST` superglobal.

Suppose you have an HTML form like this:

<form method="post" action="process.php">
<input type="text" name="username">
<input type="password" name="password">
<button type="submit">Submit</button>
</form>

In the `process.php` script, you can access the form data like this:

$username = $_POST['username'];
$password = $_POST['password'];

You can then use these variables to process the submitted data.

Important Security Note:

When working with superglobals like `$_GET` and `$_POST`, it's important to validate and sanitize user inputs to prevent security vulnerabilities like SQL injection or cross-site scripting (XSS) attacks. Always validate and sanitize user inputs before using them in your application.

For example, you can use the `filter_input()` function to validate and sanitize input data:

$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
$password = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);

Always prioritize security by validating and sanitizing user inputs before using them in your application.

10. Include and Require

In PHP, `include` and `require` are used to include external files into your current script. This is useful for reusing code, organizing your codebase, and separating concerns. Here’s how they work:

Using `include`:

The `include` statement allows you to include the content of another PHP file within your current script. If the included file is not found, a warning will be issued, but the script will continue to execute.

Suppose you have a file named `header.php`:

<!-- header.php -->
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>

You can include this header in another PHP file like this:

include "header.php";
echo "<h1>Welcome to my website!</h1>";

The content of `header.php` will be inserted at the point of the `include` statement.

Using `require`:

The `require` statement works similarly to `include`, but if the included file is not found, it will produce a fatal error and stop script execution.

Suppose you have a file named `footer.php`:

<!-- footer.php -->
</body>
</html>

You can require this footer in your PHP file like this:

echo "<p>Thank you for visiting.</p>";
require "footer.php";

The content of `footer.php` will be inserted at the point of the `require` statement.

Using `include_once` and `require_once`:

To ensure that a file is included only once, you can use `include_once` and `require_once`. These statements prevent multiple inclusions and avoid errors caused by redefining functions or classes.

include_once "header.php"; // Includes header only once
require_once "config.php"; // Requires config only once

Summary:

- `include` and `require` are used to include external PHP files.
- `include` will continue script execution even if the file is missing.
- `require` will stop script execution with an error if the file is missing.
- `include_once` and `require_once` ensure a file is included only once.

Conclusion

Mastering these essential PHP syntax elements will provide you with a solid foundation to build dynamic web applications. As you progress, you'll delve into more advanced topics like database interaction and object-oriented programming. Keep practicing, exploring, and experimenting to unlock the full potential of PHP.

--

--