PHP is a server-side scripting language used to build dynamic websites, web applications, APIs, and command-line scripts. It runs on the server, processes logic (like talking to databases, validating forms, or handling logins), and then sends the final HTML (or JSON, XML, etc.) to the browser.
Common uses of PHP:
* Building full web apps (blogs, forums, CRMs, e-commerce sites)
* Handling form submissions (login, signup, contact forms)
* Working with databases (MySQL, PostgreSQL, etc.)
* Building REST APIs or backends for mobile apps
* Generating dynamic pages (user dashboards, profile pages, admin panels)
* Powering frameworks and CMSs like Laravel, WordPress, Symfony, etc.
Important things to understand in PHP:
* Basic syntax and how PHP blocks work
* Variables and data types
* Operators and expressions
* Control structures (if, else, switch)
* Loops (for, while, foreach)
* Functions
* Arrays and strings
* Superglobals like `$_GET`, `$_POST`, `$_SESSION`
* Basic OOP (classes, objects)
* How PHP connects to databases
* How frameworks like Laravel sit on top of PHP
1. Basic PHP Syntax
PHP code usually lives inside `<?php … ?>` tags.
“`php
<?php
echo “Hello, world!”;
?>
“`
* `echo` outputs data to the browser.
* Lines usually end with a semicolon `;`.
* PHP code can be embedded inside HTML.
Example mixing HTML and PHP:
“`php
<!DOCTYPE html>
<html>
<body>
<h1>My Page</h1>
<p>
<?php
echo “This content is generated by PHP.”;
?>
</p>
</body>
</html>
“`
2. Comments
Comments are parts of the code that PHP ignores. Used for notes and explanations.
“`php
<?php
// Single line comment
# Another single line comment
/*
Multi-line comment
spanning several lines
*/
?>
“`
3. Variables
A variable stores a value. In PHP:
* Variables start with `$`
* They are loosely typed (no need to declare type)
* They are case-sensitive
“`php
<?php
$name = “Spider”;
$age = 20;
$height = 1.75;
$isAdmin = true;
echo $name;
?>
“`
Naming rules:
* Must start with `$`
* Then a letter or underscore
* Can contain letters, numbers, underscores
* No spaces
4. Data Types
Common PHP data types:
* **String** – text, e.g. `”hello”`
* **Integer** – whole numbers, e.g. `10`, `-5`
* **Float (Double)** – decimals, e.g. `3.14`
* **Boolean** – `true` or `false`
* **Array** – collection of values
* **Object** – instance of a class
* **NULL** – variable with no value
Example:
“`php
<?php
$city = “Nairobi”; // string
$year = 2025; // integer
$score = 99.5; // float
$isOnline = true; // boolean
$user = null; // NULL
?>
“`
Use `var_dump()` to inspect variables:
“`php
var_dump($city);
“`
5. Strings
Strings represent text. You can use single or double quotes.
“`php
<?php
$name = “Spider”;
$greeting = ‘Hello’;
echo “$greeting, $name”; // double quotes: variables are parsed
echo ‘$greeting, $name’; // single quotes: treated as plain text
?>
“`
String functions:
“`php
<?php
$text = “PHP is awesome”;
echo strlen($text); // length
echo strtoupper($text); // to upper case
echo strtolower($text); // to lower case
echo str_replace(“awesome”, “powerful”, $text); // replace
echo substr($text, 0, 3); // “PHP”
?>
“`
Concatenation uses the dot `.`:
“`php
<?php
$firstName = “Spider”;
$lastName = “Dev”;
$fullName = $firstName . ” ” . $lastName;
echo $fullName;
?>
“`
—
6. Numbers and Operators
# Arithmetic operators
“`php
<?php
$a = 10;
$b = 3;
echo $a + $b; // addition
echo $a – $b; // subtraction
echo $a * $b; // multiplication
echo $a / $b; // division
echo $a % $b; // modulus (remainder)
?>
“`
# Assignment operators
“`php
<?php
$x = 5;
$x += 2; // $x = $x + 2
$x -= 1; // $x = $x – 1
$x *= 3; // $x = $x * 3
$x /= 2; // $x = $x / 2
?>
“`
# Comparison operators
Used in conditions. They return `true` or `false`.
“`php
<?php
$a == $b // equal
$a === $b // identical (value and type)
$a != $b // not equal
$a !== $b // not identical
$a > $b
$a < $b
$a >= $b
$a <= $b
?>
“`
# Logical operators
Combine conditions.
“`php
<?php
&& // AND
|| // OR
! // NOT
?>
“`
Example:
“`php
<?php
$age = 20;
$isMember = true;
if ($age >= 18 && $isMember) {
echo “Access granted.”;
}
?>
“`
## 7. Arrays
Arrays store multiple values in one variable.
# Indexed arrays
“`php
<?php
$fruits = [“apple”, “banana”, “orange”];
echo $fruits[0]; // “apple”
echo $fruits[1]; // “banana”
?>
“`
# Associative arrays
Arrays with keys (like dictionaries):
“`php
<?php
$user = [
“name” => “Spider”,
“email” => “spider@example.com”,
“age” => 21,
];
echo $user[“name”];
echo $user[“email”];
?>
“`
# Array functions
“`php
<?php
$numbers = [1, 2, 3];
array_push($numbers, 4); // add at end
array_pop($numbers); // remove last
$count = count($numbers); // length
print_r($numbers); // print array in readable format
?>
“`
8. Conditionals (if, else, elseif, switch)
# If / else
“`php
<?php
$score = 75;
if ($score >= 80) {
echo “Grade A”;
} elseif ($score >= 60) {
echo “Grade B”;
} else {
echo “Grade C or below”;
}
?>
“`
# Ternary operator (short if)
“`php
<?php
$age = 18;
$message = ($age >= 18) ? “Adult” : “Minor”;
echo $message;
?>
“`
# Switch
Useful for many conditions on the same variable.
“`php
<?php
$day = “Monday”;
switch ($day) {
case “Monday”:
echo “Start of the week”;
break;
case “Friday”:
echo “Almost weekend”;
break;
default:
echo “Just another day”;
break;
}
?>
“`
9. Loops (brief)
Loops repeat blocks of code.
# While loop
“`php
<?php
$i = 1;
while ($i <= 5) {
echo “Number: $i<br>”;
$i++;
}
?>
“`
# For loop
“`php
<?php
for ($i = 1; $i <= 5; $i++) {
echo “Iteration: $i<br>”;
}
?>
“`
# Foreach loop (great for arrays)
“`php
<?php
$fruits = [“apple”, “banana”, “orange”];
foreach ($fruits as $fruit) {
echo $fruit . “<br>”;
}
?>
“`
With keys:
“`php
<?php
$user = [
“name” => “Spider”,
“role” => “Developer”,
];
foreach ($user as $key => $value) {
echo “$key: $value<br>”;
}
?>
“`
10. Functions
Functions group reusable code.
“`php
<?php
function greet($name) {
return “Hello, $name”;
}
echo greet(“Spider”);
echo greet(“Tristan”);
?>
“`
Default parameters:
“`php
<?php
function sum($a = 0, $b = 0) {
return $a + $b;
}
echo sum(3, 4); // 7
echo sum(5); // 5 + 0 = 5
?>
“`
11. Superglobals (`$_GET`, `$_POST`, `$_SERVER`, etc.)
Superglobals are built-in variables always available.
* `$_GET` – data from the URL query string
* `$_POST` – data from a form submitted via POST
* `$_SERVER` – server and request info
* `$_SESSION` – session data
* `$_COOKIE` – cookie data
Example: reading a value from URL like `page.php?name=Spider`:
“`php
<?php
$name = $_GET[‘name’] ?? ‘Guest’;
echo “Hello, $name”;
?>
“`
Form handling (basic idea):
“`html
<form method=”post” action=”submit.php”>
<input type=”text” name=”email”>
<button type=”submit”>Send</button>
</form>
“`
“`php
<?php
// submit.php
$email = $_POST[’email’] ?? null;
if ($email) {
echo “Submitted email: ” . htmlspecialchars($email);
}
?>
“`
Use `htmlspecialchars()` to prevent basic XSS issues when outputting user input.
12. Sessions and Cookies (brief)
#Sessions
Sessions store user data across multiple requests (e.g., logged-in user).
“`php
<?php
session_start(); // start session at top of script
$_SESSION[‘user’] = “Spider”;
echo $_SESSION[‘user’]; // access later
?>
“`
Destroy session:
“`php
<?php
session_start();
session_destroy();
?>
“`
# Cookies
Cookies are stored on the client.
“`php
<?php
setcookie(“theme”, “dark”, time() + 3600); // 1 hour
if (isset($_COOKIE[‘theme’])) {
echo “Theme: ” . $_COOKIE[‘theme’];
}
?>
“`
13. Basic OOP in PHP (very light intro)
PHP supports object-oriented programming.
# Class and object
“`php
<?php
class User {
public $name;
public function __construct($name) {
$this->name = $name;
}
public function greet() {
return “Hello, ” . $this->name;
}
}
$user = new User(“Spider”);
echo $user->greet();
?>
“`
* `class` defines a blueprint
* `$this` refers to the current object
* `__construct` is the constructor method
OOP becomes very important in frameworks like Laravel.
14. Working with Databases (PDO example)
To connect PHP to a database like MySQL, use PDO.
“`php
<?php
$host = “localhost”;
$db = “my_database”;
$user = “root”;
$pass = “password”;
try {
$dsn = “mysql:host=$host;dbname=$db;charset=utf8mb4”;
$pdo = new PDO($dsn, $user, $pass);
// set error mode
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// simple SELECT
$stmt = $pdo->query(“SELECT * FROM users”);
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row[‘name’] . “<br>”;
}
} catch (PDOException $e) {
echo “DB error: ” . $e->getMessage();
}
?>
“`
This is how PHP talks to databases behind the scenes. Frameworks like Laravel wrap this logic into cleaner abstractions.
15. From Core PHP to Laravel (introduction to Laravel)
Laravel is a modern PHP framework designed to make building web applications faster, cleaner, and more organized. It sits on top of PHP and gives you:
* A clear structure (MVC: Model–View–Controller)
* Built-in routing
* Database layer (Eloquent ORM)
* Blade templating engine
* Authentication scaffolding
* Command line tool (Artisan)
* Migrations for managing database schema
* Middlewares, queues, jobs, events, and more
You still need to understand PHP basics, because Laravel is built in PHP and all controllers, models, etc. are PHP code.
# MVC in simple terms
* **Model** – represents data and business logic (e.g., `User`, `Post`)
* **View** – what the user sees (Blade templates – `.blade.php` files)
* **Controller** – handles requests and coordinates between models and views
# Typical Laravel request flow
1. User hits a URL in the browser
2. Laravel matches the URL to a route (in `routes/web.php` or `routes/api.php`)
3. The route calls a controller method
4. The controller uses models/services to fetch or modify data
5. Controller returns a view (HTML) or JSON response
Example Laravel route:
“`php
// routes/web.php
use App\Http\Controllers\HomeController;
Route::get(‘/’, [HomeController::class, ‘index’]);
“`Example controller:
“`php
// app/Http/Controllers/HomeController.php
namespace App\Http\Controllers;
use App\Models\User;
class HomeController extends Controller
{
public function index()
{
$users = User::all();
return view(‘home’, compact(‘users’));
}
}
“`
Example Blade view:
“`php
<!– resources/views/home.blade.php –>
<!DOCTYPE html>
<html>
<body>
<h1>Users</h1>
<ul>
@foreach ($users as $user)
<li>{{ $user->name }}</li>
@endforeach
</ul>
</body>
</html>
“`
# Eloquent ORM
Eloquent is Laravel’s way of talking to the database using models instead of raw SQL.
Example `User` model:
“`php
// app/Models/User.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
protected $fillable = [‘name’, ’email’];
}
“`
Using Eloquent:
“`php
// get all users
$users = User::all();
// find by id
$user = User::find(1);
// create new user
User::create([
‘name’ => ‘Spider’,
’email’ => ‘spider@example.com’,
]);
“`
# Migrations
Migrations are version control for your database schema. Instead of manually editing tables in phpMyAdmin, you write PHP files that describe the table.
Example migration:
“`php
public function up()
{
Schema::create(‘users’, function (Blueprint $table) {
$table->id();
$table->string(‘name’);
$table->string(’email’)->unique();
$table->timestamps();
});
}
“`
Then you run:
“`bash
php artisan migrate
“`
Laravel applies the migration and creates the table.
# Artisan (Laravel CLI)
Artisan is Laravel’s command-line tool.
Common commands:
“`bash
php artisan serve # start dev server
php artisan migrate # run migrations
php artisan make:model User -m
php artisan make:controller HomeController
php artisan route:list # list routes
“`
# Blade templating
Blade makes writing views simpler with directives like `@if`, `@foreach`, and using `{{ }}` for escaping variables.
Example:
“`php
<h1>Hello, {{ $name }}</h1>
@if($age >= 18)
<p>You are an adult.</p>
@else
<p>You are a minor.</p>
@endif
“`
### Why Laravel is useful
* Forces a clean structure instead of random PHP files everywhere
* Handles common tasks: routing, validation, sessions, authentication
* Helps organize large projects (like ERPs, CRM systems, dashboards)
* Integrates easily with queues, mail, notifications, APIs
* Community packages for almost everything (payments, admin panels, etc.)
—
## 16. How PHP and Laravel fit into your learning path
A simple progression that makes sense:
1. Get comfortable with core PHP:
* Variables, data types
* Strings, arrays
* If/else, loops
* Functions
* Basic OOP
* Working with forms and sessions
2. Understand how a basic PHP app works:
* One file handling a request
* Include/require files to organize code
* Connect to a database using PDO or MySQLi
* Perform CRUD operations (Create, Read, Update, Delete)
3. Move into Laravel:
* Install Laravel and run `php artisan serve`
* Learn routing and controllers
* Learn Blade views
* Learn Eloquent models and migrations
* Build something small (e.g., a task list, blog, or simple CRM module)
4. Gradually use Laravel features:
* Form requests and validation
* Authentication (login/register)
* Middlewares
* API routes and JSON responses
Once you understand PHP basics, Laravel becomes a powerful layer that speeds up everything and gives structure to your projects.