PHP (Hypertext Preprocessor) powers a significant portion of websites across the internet. If you’re new to PHP or looking to refresh your knowledge, understanding its syntax is the foundation of becoming proficient in this versatile language.
What is PHP?
PHP is a server-side scripting language designed specifically for web development. Unlike JavaScript, which runs in the browser, PHP code executes on the server and generates HTML that is then sent to the client.
Basic PHP Syntax
PHP Tags
Every PHP script starts and ends with special tags:
<?php // Your PHP code goes here ?>
You can also use the short echo tag to quickly output content:
<?= "Hello World" ?>
Statements and Semicolons
In PHP, each statement must end with a semicolon (;
). This tells the PHP interpreter that the statement is complete.
<?php echo "Hello"; $name = "Developer"; echo "Welcome, " . $name; ?>
Comments
Comments help make your code more readable and are ignored by the PHP interpreter:
<?php // This is a single-line comment /* This is a multi-line comment that spans multiple lines */ # This is also a single-line comment (shell-style) ?>
Variables
Variables in PHP start with a dollar sign ($
) followed by the variable name:
<?php $name = "John"; $age = 25; $is_programmer = true; $hourly_rate = 45.50; ?>
Variable Rules
- Variable names must start with a letter or underscore
- Variable names can only contain letters, numbers, and underscores
- Variable names are case-sensitive ($name is different from $NAME)
Data Types
PHP supports several data types:
Data Type | Example | Description |
---|---|---|
String | $text = "Hello World"; | Text enclosed in quotes |
Integer | $number = 42; | Whole numbers |
Float | $price = 19.99; | Numbers with decimal points |
Boolean | $is_active = true; | True or false values |
Array | $colors = ["red", "blue", "green"]; | Collection of values |
Object | $user = new User(); | Instance of a class |
NULL | $value = NULL; | Special variable without value |
Operators
Arithmetic Operators
<?php $a = 10; $b = 3; echo $a + $b; // Addition (13) echo $a - $b; // Subtraction (7) echo $a * $b; // Multiplication (30) echo $a / $b; // Division (3.33...) echo $a % $b; // Modulus (remainder: 1) echo $a ** $b; // Exponentiation (1000) ?>
Comparison Operators
<?php $a = 10; $b = "10"; var_dump($a == $b); // Equal (true) var_dump($a === $b); // Identical (false) var_dump($a != $b); // Not equal (false) var_dump($a !== $b); // Not identical (true) var_dump($a > 5); // Greater than (true) var_dump($a <= 10); // Less than or equal to (true) ?>
Logical Operators
<?php $a = true; $b = false; var_dump($a && $b); // AND (false) var_dump($a || $b); // OR (true) var_dump(!$a); // NOT (false) ?>
Conditional Statements
If/Else Statements
<?php $age = 18; if ($age < 18) { echo "You are a minor."; } elseif ($age == 18) { echo "You just became an adult!"; } else { echo "You are an adult."; } ?>
Switch Statement
<?php $day = "Monday"; switch ($day) { case "Monday": echo "Start of work week"; break; case "Friday": echo "End of work week"; break; case "Saturday": case "Sunday": echo "Weekend!"; break; default: echo "Midweek day"; } ?>
Loops
For Loop
<?php for ($i = 0; $i < 5; $i++) { echo "Number: $i <br>"; } ?>
While Loop
<?php $counter = 0; while ($counter < 5) { echo "Count: $counter <br>"; $counter++; } ?>
Foreach Loop (for arrays)
<?php $fruits = ["Apple", "Banana", "Cherry"]; foreach ($fruits as $fruit) { echo "$fruit <br>"; } // With key $person = [ "name" => "John", "age" => 30, "city" => "New York" ]; foreach ($person as $key => $value) { echo "$key: $value <br>"; } ?>
Functions
Functions encapsulate code that you can reuse:
<?php // Defining a function function greet($name) { return "Hello, $name!"; } // Calling the function echo greet("Sarah"); // Outputs: Hello, Sarah! // Function with default parameter function add($a, $b = 5) { return $a + $b; } echo add(10); // Outputs: 15 echo add(10, 20); // Outputs: 30 ?>
Arrays
PHP supports both indexed and associative arrays:
<?php // Indexed array $colors = ["Red", "Green", "Blue"]; echo $colors[0]; // Outputs: Red // Associative array $user = [ "name" => "John", "email" => "john@example.com", "active" => true ]; echo $user["email"]; // Outputs: john@example.com // Multidimensional array $employees = [ ["John", "Developer", 75000], ["Sarah", "Designer", 65000], ["Mike", "Manager", 85000] ]; echo $employees[1][0]; // Outputs: Sarah ?>
Frequently Asked Questions
What are the differences between single and double quotes in PHP?
Single Quotes (' ) | Double Quotes (" ) |
---|---|
Literal string | Interprets variables |
More efficient | Allows escape sequences |
No variable parsing | Variables are parsed |
Example:
<?php $name = "John"; echo 'Hello $name'; // Outputs: Hello $name echo "Hello $name"; // Outputs: Hello John ?>
How do I include one PHP file in another?
PHP provides several ways to include files:
<?php include 'header.php'; // Continues if file not found require 'functions.php'; // Fatal error if file not found include_once 'config.php'; // Include only if not included before require_once 'database.php'; // Require only if not included before ?>
What’s the difference between GET and POST in PHP?
GET | POST |
---|---|
Data sent in URL | Data sent in request body |
Visible in browser address bar | Not visible in browser address bar |
Limited to ~2000 characters | No size limitation |
Can be bookmarked | Cannot be bookmarked |
Shouldn’t be used for sensitive data | Better for sensitive data |
Example:
<?php // Accessing GET data $search = $_GET['search'] ?? ''; // Accessing POST data $username = $_POST['username'] ?? ''; ?>
How do I connect to a database using PHP?
Using PDO (PHP Data Objects):
<?php try { $pdo = new PDO("mysql:host=localhost;dbname=mydb", "username", "password"); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?"); $stmt->execute([1]); $user = $stmt->fetch(); echo $user['name']; } catch(PDOException $e) { echo "Connection failed: " . $e->getMessage(); } ?>
Best Practices for PHP Syntax
- Always use opening and closing tags: Even if your file contains only PHP code, it’s good practice to include them.
- Be consistent with quotes: Choose single or double quotes and be consistent throughout your project.
- Indent your code: Use consistent indentation (tabs or spaces) to make your code more readable.
- Comment your code: Add comments to explain complex sections of your code.
- Use meaningful variable names:
$user_age
is more descriptive than$ua
. - Always validate user input: Never trust input from users. Sanitize and validate all data.
- Error handling: Use try/catch blocks when working with operations that might fail.
- Close database connections: When you’re done with a database connection, close it to free up resources.
Conclusion
This guide covers the basic syntax of PHP that you’ll need to get started with the language. As you become more comfortable with these fundamentals, you can explore more advanced features like object-oriented programming, namespaces, and working with external libraries.
Remember, practice is key to mastering PHP or any programming language. The more you code, the more familiar the syntax will become, and you’ll be building dynamic web applications in no time!
For more resources and examples, check out the official PHP documentation.