PHP Syntax and Basics

Part of the course: php for beginners

PHP Syntax and Basics

PHP Syntax and Basics

1. Introduction to PHP

1.1 What is PHP?

PHP (Hypertext Preprocessor) is a widely used server-side scripting language designed primarily for web development. It is embedded into HTML, allowing developers to create dynamic web pages that can interact with databases, handle forms, manage sessions, and more.

  • PHP code runs on the server, and the result (usually HTML) is sent to the client’s browser.

  • It is open-source, cross-platform, and supports integration with various databases (e.g., MySQL, PostgreSQL).

  • PHP is known for its simplicity, flexibility, and large community support.

Example:

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

1.2 History and Evolution of PHP

PHP was created in 1994 by Rasmus Lerdorf to track visits to his online résumé. Initially called “Personal Home Page Tools,” it evolved into a full-fledged programming language.

  • PHP 3 (1998): Introduced as a robust scripting language.

  • PHP 4 (2000): Introduced the Zend Engine for better performance.

  • PHP 5 (2004): Brought object-oriented programming (OOP) features.

  • PHP 7 (2015): Improved performance and introduced type declarations.

  • PHP 8 (2020): Added JIT (Just-In-Time) compilation and new language features.

Today, PHP powers millions of websites, including major platforms like WordPress, Wikipedia, and Facebook (in its early days).

1.3 How PHP Works (Server-Side Execution)

PHP operates on the server-side, meaning the code is executed on the web server before being sent to the user’s browser.
Here’s how it works:

  1. The user requests a .php page from the web browser.

  2. The web server (like Apache or Nginx) passes the request to the PHP interpreter.

  3. The PHP engine processes the code and generates output (usually HTML).

  4. The final output is sent back to the browser for display.

Key point:
The user never sees the actual PHP code—only the output.

1.4 Setting Up a PHP Environment (XAMPP, WAMP, LAMP)

To run PHP locally, you need a server environment that includes:

  • Apache/Nginx (web server)

  • MySQL/MariaDB (database)

  • PHP (scripting engine)

Common setup options:

  • XAMPP (Windows/Linux/macOS): All-in-one package (Apache, MySQL, PHP, Perl).

  • WAMP (Windows): Apache, MySQL, and PHP stack for Windows users.

  • LAMP (Linux): Linux, Apache, MySQL, and PHP for Linux servers.

  • MAMP (macOS): Similar to WAMP but for macOS.

After installation, you can create PHP files in the htdocs (or www) directory and access them via:

http://localhost/yourfile.php

2. Basic PHP Syntax

2.1 PHP Tags (<?php ... ?>)

Basic PHP Syntax

PHP code is embedded inside special tags that tell the server where the PHP script begins and ends.
The most common tag is:

<?php
// PHP code goes here
?>

Anything written inside <?php ... ?> will be processed by the PHP engine.

There are a few other types of tags, but the full tag (<?php ... ?>) is the most recommended and universally supported:

  • Short open tag: <? ... ?> (not recommended — may not be enabled on all servers)

  • ASP-style tags: <% ... %> (deprecated)

  • Script tag: <script language="php"> ... </script> (rarely used)

Example:

<!DOCTYPE html>
<html>
<body>
<h1><?php echo "Welcome to PHP!"; ?></h1>
</body>
</html>

The PHP code above is executed on the server, and the browser only receives:

<h1>Welcome to PHP!</h1>

2.2 Comments in PHP

Comments are notes you write in your code to explain what it does. They are ignored by the PHP interpreter.

There are three types of comments in PHP:

<?php
// This is a single-line comment using double slashes
# This is also a single-line comment using hash

/*
This is a multi-line comment.
You can write several lines here.
*/

?>

Best practice: Use comments to describe complex logic or important sections of your code — not to explain obvious things.

2.3 Case Sensitivity in PHP

PHP is partially case-sensitive:

  • Keywords, functions, and control structures (like if, else, while, echo) are not case-sensitive.

  • Variable names are case-sensitive.

Example:

<?php
$color = "blue";
echo $color; // Works
echo $Color; // Error! Undefined variable
?>

However:

<?php
ECHO "Hello!"; // Works
echo "World!"; // Also works
?>

It’s best to follow consistent casing conventions (e.g., lowercase for functions and variables, uppercase for constants).

2.4 PHP Statements and Semicolons

A statement in PHP is an instruction that performs an action — for example, assigning a value or printing text.
Each statement must end with a semicolon (;).

Example:

<?php
$a = 10;
$b = 20;
echo $a + $b; // Outputs 30
?>

If you forget a semicolon, PHP will show a syntax error and stop executing the script.

Tip:
You can write multiple statements on one line, but it reduces readability:

<?php $x=5; $y=10; echo $x+$y; ?>

It’s better to write each statement on a new line for clarity.

3. PHP Variables

3.1 Declaring Variables

A variable in PHP is a container used to store data, such as numbers, text, or arrays, that can be used and modified throughout a program.
In PHP, all variables start with a dollar sign ($) followed by the variable name.

Example:

<?php
$name = "John";
$age = 25;
echo "My name is $name and I am $age years old.";
?>

Output:

My name is John and I am 25 years old.
  • You don’t need to declare a variable’s data type explicitly. PHP automatically determines the type based on the value assigned.

  • You can reassign a new value or even a new type to the same variable later.

Example:

$x = 10; // integer
$x = "Hello"; // string — PHP automatically changes the type

3.2 Variable Naming Rules

When naming PHP variables, follow these rules:

  1. A variable name must start with a $ sign.

  2. The first character after $ must be a letter or underscore (_).

  3. The name can contain letters, numbers, and underscores.

  4. Variable names cannot contain spaces.

  5. Variable names are case-sensitive ($name and $Name are different).

Valid variable names:

$first_name
$_userID
$total3

Invalid variable names:

$3total // starts with a number
$user-name // contains a hyphen
$ first // contains a space

Best practice:
Use descriptive variable names — for example, $totalPrice instead of $tp.

3.3 Variable Scope (Local, Global, Static)

The scope of a variable determines where in your script it can be accessed. PHP has three main types of variable scope:

1. Local Scope

Variables declared inside a function can only be accessed within that function.

<?php
function test() {
$x = 10; // local variable
echo $x;
}
test();
echo $x; // Error! $x is not available outside the function
?>

2. Global Scope

Variables declared outside of any function are considered global and can only be accessed outside functions.
To use them inside a function, you must use the global keyword.

<?php
$x = 5;
$y = 10;

function add() {
global $x, $y;
echo $x + $y; // Access global variables
}
add(); // Outputs 15
?>

Alternatively, you can use the $GLOBALS array:

<?php
$x = 5;
$y = 10;

function add() {
echo $GLOBALS[‘x’] + $GLOBALS[‘y’];
}
add(); // Outputs 15
?>

3. Static Scope

When a function ends, normally all local variables are deleted.
However, if you declare a variable as static, its value is preserved between function calls.

<?php
function counter() {
static $count = 0;
$count++;
echo $count . "<br>";
}
counter(); // 1
counter(); // 2
counter(); // 3
?>

3.4 Variable Variables

A variable variable means that the name of a variable is stored in another variable.

Example:

<?php
$varName = "color";
$$varName = "blue"; // Creates a variable $color
echo $color; // Outputs: blue
?>

Explanation:

  • $varName holds the string "color".

  • $$varName means “the variable whose name is the value of $varName,” which becomes $color.

Be cautious: While variable variables can be powerful, they can also make your code harder to read and debug. They are best used in special cases, not general code.

4. Data Types and Type Casting

In PHP, a data type defines the kind of value a variable can hold.
PHP is a loosely typed language, which means you don’t need to declare variable types explicitly — PHP automatically converts them depending on context.

There are eight primary data types in PHP:

4.1 String

A string is a sequence of characters enclosed in quotes (single ' ' or double " ").
It is used to store text.

Example:

<?php
$name = "Alice";
echo "Hello, $name!"; // Double quotes allow variable parsing
echo 'Hello, $name!'; // Single quotes do not parse variables
?>

Output:

Hello, Alice!
Hello, $name!

Common string functions:

  • strlen($str) → Returns the length of a string

  • strtoupper($str) / strtolower($str) → Converts case

  • str_replace("old","new",$str) → Replaces text

  • strpos($str,"word") → Finds the position of a substring

4.2 Integer

An integer is a whole number (positive, negative, or zero) without decimals.

Example:

<?php
$age = 30;
$year = -2025;
echo $age + $year;
?>

Rules:

  • Must contain at least one digit

  • Cannot have decimals

  • Can be written in decimal, hexadecimal (0x), or octal (0) format

Example:

<?php
$a = 255; // decimal
$b = 0xFF; // hexadecimal
$c = 0377; // octal
?>

4.3 Float (Double)

A float or double represents a number with a decimal point or an exponent form.

Example:

<?php
$price = 19.99;
$tax = 0.07;
$total = $price + ($price * $tax);
echo $total; // 21.3893
?>

Floats are used for calculations that require precision — but keep in mind that floating-point arithmetic may sometimes produce rounding errors.

4.4 Boolean

A Boolean has only two possible values:

  • TRUE or FALSE (not case-sensitive).

Booleans are commonly used in conditions and control structures.

Example:

<?php
$is_logged_in = true;

if ($is_logged_in) {
echo “Welcome!”;
} else {
echo “Please log in.”;
}
?>

Output:

Welcome!

4.5 Array

An array is a variable that stores multiple values under a single name.
Each value is stored at an index, which can be a number or string (key).

Example:

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

There are three main types of arrays:

  1. Indexed arrays — use numeric indexes

  2. Associative arrays — use named keys

  3. Multidimensional arrays — contain other arrays

Example (associative):

<?php
$person = array("name" => "John", "age" => 25);
echo $person["name"]; // John
?>

4.6 Object

An object is a data type that stores both data and functions (methods) in a single entity.
Objects are created from classes.

Example:

<?php
class Car {
public $color;
function setColor($c) {
$this->color = $c;
}
}

$myCar = new Car();
$myCar->setColor(“red”);
echo $myCar->color; // Outputs: red
?>

Objects are the foundation of object-oriented programming (OOP) in PHP.

4.7 NULL

The NULL type represents a variable with no value.
A variable becomes NULL if:

  • It has been explicitly assigned NULL

  • It has not been assigned any value yet

  • It has been unset using unset()

Example:

<?php
$x = null;
var_dump($x); // Outputs: NULL
?>

4.8 Type Casting and Type Juggling

PHP automatically converts data types when necessary — this is called type juggling.

Example:

<?php
$x = "5";
$y = 10;
echo $x + $y; // PHP converts "5" (string) to integer automatically → 15
?>

You can also manually convert (type cast) a variable’s data type:

<?php
$a = 5.75;
$b = (int)$a; // Converts float to integer
echo $b; // Outputs: 5
?>

Common type casting options:

  • (int) or (integer)

  • (float) or (double)

  • (string)

  • (bool) or (boolean)

  • (array)

  • (object)

  • (unset)

 

 

5. Constants

A constant is a name or identifier for a simple value that cannot be changed during the execution of a script.
Unlike variables, constants do not use a dollar sign ($) before their name, and once defined, their value remains fixed throughout the program.

Constants are useful for storing values that should stay the same, such as configuration settings, file paths, or version numbers.

Example:

<?php
define("SITE_NAME", "My Website");
echo SITE_NAME; // Outputs: My Website
?>

5.1 Defining Constants with define()

The most common way to create a constant in PHP is by using the define() function.

Syntax:

define(name, value, case_insensitive);
  • name → The name of the constant (string, without $)

  • value → The constant value (can be any scalar type — string, number, boolean, etc.)

  • case_insensitive (optional) → If true, the constant name is not case-sensitive (deprecated in PHP 8)

Example:

<?php
define("PI", 3.14159);
echo PI; // Outputs: 3.14159
?>

Note:

  • Constants are global by default and can be accessed anywhere in the script.

  • As of PHP 8.0, constant names are always case-sensitive.

5.2 Using const Keyword

You can also define constants using the const keyword.
This method is often preferred inside classes or namespaces.

Syntax:

const NAME = value;

Example (global constant):

<?php
const SITE_URL = "https://example.com";
echo SITE_URL;
?>

Example (inside a class):

<?php
class Math {
const PI = 3.14159;
}

echo Math::PI; // Accessing class constant
?>

Key Differences Between define() and const:

Feature define() const
Can be used inside classes ❌ No ✅ Yes
Supports dynamic values ✅ Yes ❌ No (must be known at compile time)
Case-insensitive option ✅ (deprecated) ❌ No
Works inside conditional blocks ✅ Yes ❌ No

5.3 Magic Constants

Magic constants are predefined constants in PHP that change depending on where they are used.
They always start and end with double underscores (__).

Here are the most commonly used magic constants:

Constant Description Example Output
__LINE__ Returns the current line number in the file. 12
__FILE__ Returns the full path and filename of the file. /var/www/html/index.php
__DIR__ Returns the directory of the file. /var/www/html
__FUNCTION__ Returns the name of the current function. myFunction
__CLASS__ Returns the name of the current class. User
__METHOD__ Returns the name of the current class method. User::login
__NAMESPACE__ Returns the current namespace name. App\Controllers

Example:

<?php
echo "This line is " . __LINE__ . "<br>";
echo "This file is " . __FILE__ . "<br>";
echo "This directory is " . __DIR__ . "<br>";

function test() {
echo “Function name: “ . __FUNCTION__;
}
test();
?>

Output (example):

This line is 3
This file is /var/www/html/test.php
This directory is /var/www/html
Function name: test

Summary:

  • Use constants for values that should not change.

  • Define them using either define() or const.

  • Magic constants provide useful contextual information about your script.

 

6. Operators

Operators in PHP are symbols or keywords used to perform operations on variables and values.
They are the foundation of any program’s logic — enabling you to calculate, compare, assign, and manipulate data.

In PHP, operators are grouped by their function. Let’s go through each group with examples.

6.1 Arithmetic Operators

Arithmetic operators are used to perform mathematical calculations.

Operator Name Example Result
+ Addition $x + $y Sum of $x and $y
- Subtraction $x - $y Difference of $x and $y
* Multiplication $x * $y Product of $x and $y
/ Division $x / $y Quotient of $x and $y
% Modulus $x % $y Remainder of $x divided by $y
** Exponentiation $x ** $y $x raised to the power $y

Example:

<?php
$x = 10;
$y = 3;

echo $x + $y; // 13
echo $x % $y; // 1
echo $x ** $y; // 1000
?>

6.2 Assignment Operators

Assignment operators are used to assign values to variables.
The most basic one is the equal sign (=), but there are also compound assignments for shorthand calculations.

Operator Example Equivalent To
= $x = $y Assign value of $y to $x
+= $x += $y $x = $x + $y
-= $x -= $y $x = $x - $y
*= $x *= $y $x = $x * $y
/= $x /= $y $x = $x / $y
%= $x %= $y $x = $x % $y

Example:

<?php
$x = 5;
$x += 3; // same as $x = $x + 3
echo $x; // 8
?>

6.3 Comparison Operators

Comparison operators are used to compare two values and return a Boolean (true or false).

Operator Description Example Result
== Equal $x == $y True if $x equals $y
=== Identical $x === $y True if $x and $y are equal and of the same type
!= or <> Not equal $x != $y True if $x is not equal to $y
!== Not identical $x !== $y True if $x and $y are not equal or not the same type
> Greater than $x > $y True if $x is greater than $y
< Less than $x < $y True if $x is less than $y
>= Greater than or equal to $x >= $y True if $x$y
<= Less than or equal to $x <= $y True if $x$y
<=> Spaceship $x <=> $y Returns -1, 0, or 1 depending on comparison result

Example:

<?php
$x = 10;
$y = "10";

var_dump($x == $y); // true (same value)
var_dump($x === $y); // false (different types)
var_dump($x <=> $y); // 0 (equal)
?>

6.4 Logical Operators

Logical operators are used to combine conditional statements.
They are often used in if statements to control program flow.

Operator Name Example Result
and or && Logical AND $x && $y True if both are true
or or ` ` Logical OR
! Logical NOT !$x True if $x is false
xor Exclusive OR $x xor $y True if only one is true

Example:

<?php
$age = 20;
$hasID = true;

if ($age >= 18 && $hasID) {
echo “Access granted.”;
} else {
echo “Access denied.”;
}
?>

Output:

Access granted.

6.5 String Operators

String operators are used to combine or manipulate text strings.

Operator Name Example Result
. Concatenation $x . $y Joins two strings
.= Concatenation assignment $x .= $y Appends $y to $x

Example:

<?php
$first = "Hello";
$second = "World";
echo $first . " " . $second; // Hello World

$first .= ” PHP!”;
echo $first; // Hello PHP!
?>

6.6 Increment / Decrement Operators

These operators are used to increase or decrease a variable’s value by 1.
They are often used in loops.

Operator Name Example Description
++$x Pre-increment Increments $x by 1, then returns $x
$x++ Post-increment Returns $x, then increments it by 1
--$x Pre-decrement Decreases $x by 1, then returns $x
$x-- Post-decrement Returns $x, then decreases it by 1

Example:

<?php
$x = 5;
echo ++$x; // 6 (increments first)
echo $x++; // 6 (prints, then increments to 7)
echo $x; // 7
?>

6.7 Array Operators

Array operators are used to compare or combine arrays.

Operator Description Example
+ Union of arrays $x + $y
== True if arrays have same key/value pairs $x == $y
=== True if arrays have same key/value pairs in the same order and type $x === $y
!= or <> True if arrays are not equal $x != $y
!== True if arrays are not identical $x !== $y

Example:

<?php
$a = array("color" => "red", "size" => "medium");
$b = array("color" => "red", "size" => "medium");

var_dump($a == $b); // true
var_dump($a === $b); // true
?>

Summary:

  • Arithmetic → Perform math operations.

  • Assignment → Assign or update variable values.

  • Comparison → Compare values and types.

  • Logical → Combine multiple conditions.

  • String → Join and manipulate text.

  • Increment/Decrement → Change variable values by one.

  • Array → Compare or merge arrays.

 

 

7. Control Structures

Control structures in PHP determine the flow of execution in a program.
They let you make decisions, repeat actions, or skip certain parts of code based on conditions.

In this section, we’ll cover the most common control structures:
if, else, elseif, switch, for, while, do-while, foreach, and the break and continue statements.

7.1 If, Else, Elseif Statements

These are conditional statements that allow you to execute certain blocks of code depending on whether a condition is true or false.

1. if Statement

Executes a block of code if a specified condition is true.

<?php
$age = 18;
if ($age >= 18) {
echo "You are an adult.";
}
?>

Output:

You are an adult.

2. if…else Statement

If the condition is false, the code inside the else block runs.

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

Output:

You are a minor.

3. if…elseif…else Statement

Used when you need to test multiple conditions.

<?php
$score = 75;

if ($score >= 90) {
echo “Grade: A”;
} elseif ($score >= 70) {
echo “Grade: B”;
} elseif ($score >= 50) {
echo “Grade: C”;
} else {
echo “Fail”;
}
?>

Output:

Grade: B

Tip:

PHP also supports short-hand syntax for simple conditions:

<?php
echo ($age >= 18) ? "Adult" : "Minor";
?>

7.2 Switch Statement

The switch statement is used to compare one expression against multiple possible values.
It’s an alternative to multiple if...elseif statements.

Syntax:

switch (expression) {
case value1:
// Code to execute if expression == value1
break;
case value2:
// Code to execute if expression == value2
break;
default:
// Code to execute if no match is found
}

Example:

<?php
$day = "Monday";

switch ($day) {
case “Monday”:
echo “Start of the work week.”;
break;
case “Friday”:
echo “Almost weekend!”;
break;
case “Sunday”:
echo “Rest day.”;
break;
default:
echo “Just another day.”;
}
?>

Output:

Start of the work week.

Important:

  • Always use break to stop execution after a match.

  • The default case runs if no match is found.

7.3 Loops: for, while, do-while, foreach

Loops allow you to repeat a block of code as long as a condition is true.

1. for Loop

Used when you know exactly how many times you want to execute code.

Syntax:

for (initialization; condition; increment) {
// Code to execute
}

Example:

<?php
for ($i = 1; $i <= 5; $i++) {
echo "Number: $i<br>";
}
?>

Output:

Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

2. while Loop

Executes a block of code as long as a condition is true.

Example:

<?php
$count = 1;
while ($count <= 3) {
echo "Count is $count<br>";
$count++;
}
?>

Output:

Count is 1
Count is 2
Count is 3

3. do…while Loop

Similar to while, but it executes the block at least once, even if the condition is false.

Example:

<?php
$num = 5;
do {
echo "Number is $num<br>";
$num++;
} while ($num < 5);
?>

Output:

Number is 5

(The loop runs once even though $num < 5 is false.)

4. foreach Loop

Used specifically for arrays. It iterates over each element automatically.

Example 1 – Indexed Array:

<?php
$colors = array("Red", "Green", "Blue");
foreach ($colors as $color) {
echo "$color<br>";
}
?>

Example 2 – Associative Array:

<?php
$person = array("Name" => "John", "Age" => 25, "City" => "London");
foreach ($person as $key => $value) {
echo "$key: $value<br>";
}
?>

Output:

Name: John
Age: 25
City: London

7.4 Break and Continue

break Statement

Used to exit a loop or switch statement immediately when a condition is met.

Example:

<?php
for ($i = 1; $i <= 10; $i++) {
if ($i == 5) break;
echo $i . " ";
}
?>

Output:

1 2 3 4

continue Statement

Used to skip the rest of the current iteration and move to the next one.

Example:

<?php
for ($i = 1; $i <= 5; $i++) {
if ($i == 3) continue;
echo $i . " ";
}
?>

Output:

1 2 4 5

Summary:

  • Use if, else, and elseif to control decisions.

  • Use switch for multiple discrete value checks.

  • Use loops (for, while, do-while, foreach) to repeat code efficiently.

  • Use break to exit a loop early, and continue to skip an iteration.

8. Including Files

In PHP, including files allows you to reuse code by importing it from other files.
This is extremely useful for maintaining consistent layouts (like headers and footers), managing large projects, and following the DRY principle (Don’t Repeat Yourself).

For example, instead of writing the same navigation menu or database connection code in every file, you can write it once and include it wherever needed.

8.1 include and require Statements

Both include and require are used to import external PHP files into the current script.

Syntax:

include 'filename.php';
require 'filename.php';

They perform the same function but handle errors differently:

Function Behavior When File Missing
include Displays a warning and continues executing the script
require Displays a fatal error and stops the script

Example using include:

<?php
include 'header.php'; // If missing → Warning only
echo "Welcome to my website!";
?>

Example using require:

<?php
require 'config.php'; // If missing → Fatal error, script stops
echo "Database connected!";
?>

When to use which:

  • Use require for critical files (like configuration or database connections).

  • Use include for non-critical files (like optional UI components or sidebars).

8.2 include_once and require_once

The _once versions work exactly like include and require, but they ensure the file is included only one time, even if the statement is called multiple times.

This helps prevent function redefinitions, variable conflicts, or duplicate code execution.

Example:

<?php
include_once 'functions.php';
include_once 'functions.php'; // The file will only be included once

require_once 'config.php';
require_once 'config.php'; // Safe to use multiple times
?>

Why use _once versions:

  • Prevents errors when a file might be included by different scripts or multiple times.

  • Essential in large applications with many dependencies.

8.3 Best Practices for File Inclusion

To make your PHP projects organized and efficient, follow these best practices when including files:

  1. Use Absolute Paths (recommended):
    Using full paths helps avoid confusion about file locations.

    include '/var/www/html/includes/header.php';

    Or use PHP’s built-in __DIR__ constant for flexibility:

    include __DIR__ . '/includes/header.php';
  2. Use require_once for configuration files:
    This ensures important files like database configs or function libraries are included safely and only once.

  3. Organize included files in a dedicated folder:
    Keep reusable components (headers, footers, configs, functions) in a folder such as /includes or /partials.

  4. Avoid including unnecessary files:
    Including too many files can slow down performance. Only include what’s needed for that page.

  5. Handle missing files gracefully:
    If using include, check with file_exists() before including:

    if (file_exists('menu.php')) {
    include 'menu.php';
    } else {
    echo "Menu file not found.";
    }
  6. Separate logic and layout:
    Use includes to separate business logic (PHP code) from presentation (HTML templates) for better maintainability.

Summary:

  • Use include for optional files.

  • Use require for essential files.

  • Use include_once or require_once to prevent duplication.

  • Keep your project organized with modular and reusable file structures.

 

9. Functions

A function in PHP is a block of code designed to perform a specific task.
Functions help make your code more organized, reusable, and easier to maintain.

Instead of repeating the same logic in multiple places, you can write a function once and call it whenever needed.

9.1 Defining and Calling Functions

Functions are defined using the function keyword, followed by a name, parentheses (), and curly braces {} containing the code to execute.

Syntax:

function functionName() {
// Code to be executed
}

To call (execute) a function, simply use its name followed by parentheses:

function sayHello() {
echo "Hello, world!";
}

sayHello(); // Function call

Output:

Hello, world!

Important notes:

  • Function names are not case-sensitive (sayHello() and SAYHELLO() are the same).

  • Functions must be defined before they are called in the script (unless you use conditional definitions or autoloading).

9.2 Function Arguments and Return Values

Function Arguments

Functions can take parameters (arguments) that allow data to be passed in.

Example with arguments:

<?php
function greet($name) {
echo "Hello, $name!";
}

greet("Alice");
greet("Bob");
?>

Output:

Hello, Alice!
Hello, Bob!

Default Argument Values

You can set default values for parameters.
If the caller does not provide a value, the default is used.

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

greet(); // Uses default
greet("John"); // Uses provided value

Output:

Welcome, Guest!
Welcome, John!

Passing Arguments by Reference

By default, arguments are passed by value (a copy is made).
To modify the original variable, pass it by reference using &.

function addFive(&$num) {
$num += 5;
}

$value = 10;
addFive($value);
echo $value; // Outputs: 15

Return Values

A function can return a value using the return keyword.

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

$result = add(5, 7);
echo "Sum: $result";

Output:

Sum: 12

Note:
Once a return statement is executed, the function stops running immediately.

9.3 Variable Functions

PHP allows you to store a function name in a variable and call it dynamically.
This is useful for callbacks or dynamic function calls.

Example:

<?php
function sayHi() {
echo "Hi there!";
}

$func = "sayHi"; // Store function name in variable
$func(); // Call function dynamically
?>

Output:

Hi there!

Example with arguments:

function multiply($a, $b) {
return $a * $b;
}

$operation = "multiply";
echo $operation(4, 5); // 20

Use Case:
Variable functions are often used in frameworks or systems that need to call functions dynamically based on user input or configuration.

9.4 Anonymous Functions (Closures)

An anonymous function (also called a closure) is a function without a name.
It is usually stored in a variable or passed as an argument to another function.

Syntax:

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

$greet("Sarah");

Output:

Hello, Sarah!

Closures with use Keyword

Anonymous functions can inherit variables from the parent scope using the use keyword.

$message = "Good morning";
$greeter = function($name) use ($message) {
echo "$message, $name!";
};

$greeter("John");

Output:

Good morning, John!

Note:

  • Without use, the function cannot access external variables.

  • Anonymous functions are commonly used for callbacks, filtering arrays, and functional programming patterns.

Example:

$numbers = [1, 2, 3, 4, 5];

$squares = array_map(function($n) {
return $n * $n;
}, $numbers);

print_r($squares);

Output:

Array ( [0] => 1 [1] => 4 [2] => 9 [3] => 16 [4] => 25 )

Summary:

  • Use function to define reusable blocks of code.

  • Arguments allow passing data; return sends data back.

  • Variable functions allow dynamic function calls.

  • Anonymous functions (closures) are powerful for short, inline operations or callbacks.

 

 

10. Basic Input and Output

In PHP, input and output are essential for interacting with users and debugging your scripts.
Output generally involves displaying data on the browser, while input can involve user data or variable values.

10.1 echo and print Statements

PHP provides two primary statements for outputting data to the browser:

1. echo

  • echo is used to output one or more strings.

  • It can accept multiple arguments separated by commas (though this is rare).

  • It does not return a value.

Example:

<?php
echo "Hello, world!";
echo "PHP ", "is ", "fun!";
?>

Output:

Hello, world!PHP is fun!

2. print

  • print outputs a string and returns 1, which allows it to be used in expressions.

  • It accepts only one argument.

Example:

<?php
print "Hello, PHP!";
$result = print "Another line"; // Returns 1
echo $result; // 1
?>

Key Differences:

Feature echo print
Return Value None 1
Multiple Arguments Yes No
Speed Slightly faster Slightly slower

Tip:
Use echo for general output; use print when you need a return value.

10.2 Printing Variables and Strings

You can combine variables and strings in your output in several ways:

1. Concatenation using .

<?php
$name = "Alice";
echo "Hello, " . $name . "!";
?>

Output:

Hello, Alice!

2. Variable parsing in double-quoted strings

PHP automatically replaces variable names with their values inside double quotes " ".

<?php
$age = 25;
echo "I am $age years old.";
?>

Output:

I am 25 years old.

Important Notes:

  • Single quotes ' ' do not parse variables.

echo 'I am $age years old.'; // Output: I am $age years old.
  • Curly braces {} can be used for clarity when combining variables with text:

echo "My name is {$name}Smith"; // Avoids ambiguity

10.3 Using var_dump() and print_r()

These functions are mainly used for debugging because they show detailed information about variables.

1. var_dump()

  • Displays data type and value of a variable.

  • Works with all types: integers, strings, arrays, objects, etc.

Example:

<?php
$number = 42;
$text = "Hello";
$array = [1, 2, 3];

var_dump($number);
var_dump($text);
var_dump($array);
?>

Output:

int(42)
string(5) "Hello"
array(3) { [0]=> int(1) [1]=> int(2) [2]=> int(3) }

2. print_r()

  • Displays human-readable information about arrays and objects.

  • Does not show data types as clearly as var_dump().

Example:

<?php
$fruits = ["Apple", "Banana", "Cherry"];
print_r($fruits);
?>

Output:

Array
(
[0] => Apple
[1] => Banana
[2] => Cherry
)

When to Use:

  • var_dump() → Debugging when you need types and values.

  • print_r() → Debugging arrays and objects for readability.

Summary:

  • Use echo and print for general output.

  • Use concatenation or variable parsing to include variables in strings.

  • Use var_dump() and print_r() for debugging and inspecting data structures.

 

 

11. Comments and Coding Style

Writing clean, readable, and well-documented code is essential in PHP (or any programming language).
It makes your scripts easier to understand, maintain, and debug, especially in large projects or when multiple developers are involved.

11.1 Writing Readable Code

Readable code is code that can be easily understood by others — or by you, weeks or months later. Key practices include:

1. Use Comments Wisely

Comments explain why something is done, not what is done (the code itself should show that).

  • Single-line comment:

// This variable stores the user’s age
$age = 25;
  • Multi-line comment:

/*
This section handles user authentication.
It checks the username and password against the database.
*/

2. Proper Indentation

Use consistent indentation (typically 4 spaces) to show the structure of your code.

if ($age >= 18) {
echo "Adult";
} else {
echo "Minor";
}

3. Meaningful Names

Use descriptive variable, function, and class names.

$firstName = "John"; // Good
$fn = "John"; // Bad

function calculateTotal($price, $tax) { ... } // Clear

4. Keep Lines Short

Avoid very long lines. Ideally, keep lines under 80–120 characters.

5. Organize Code into Sections

Separate code logically using blank lines or comments for readability:

// Database connection
$conn = new mysqli(...);

// Fetch data
$sql = "SELECT * FROM users";
$result = $conn->query($sql);

6. Avoid Deep Nesting

Too many nested loops or conditions reduce readability. Consider breaking code into smaller functions.

11.2 PHP Coding Standards (PSR-12 Overview)

PSR-12 is the PHP-FIG standard that defines how PHP code should be formatted.
Following a standard improves consistency across projects and teams.

Key PSR-12 Guidelines

  1. Indentation

    • Use 4 spaces per indentation level (no tabs).

  2. Line Length

    • Keep lines under 120 characters.

    • Break long lines logically.

  3. Braces

    • Opening braces for classes and functions go on the next line.

class User
{
public function login()
{
// Code here
}
}
  1. Namespaces and Use Statements

    • One namespace per file.

    • use statements go after the namespace declaration and before code.

  2. Method and Function Naming

    • Use camelCase for methods and functions.

function calculateTotal() { ... }
  1. Constants

    • Use UPPER_CASE with underscores for constants.

const MAX_USERS = 100;
  1. Control Structures

    • One space after the keyword, opening brace on the same line.

if ($age >= 18) {
echo "Adult";
} else {
echo "Minor";
}
  1. Whitespace

    • Include one blank line between methods in classes.

    • Use spaces around operators and after commas.

Summary

  • Use comments to explain why, not what.

  • Follow consistent indentation, naming, and line length rules.

  • Use PSR-12 as a standard for professional, readable PHP code.

  • Clean, readable code reduces errors and makes maintenance easier.