PHP Basics
Learn PHP programming fundamentals
PHP Basics
PHP is a server-side scripting language designed for web development. This guide covers the fundamentals you need to get started with PHP programming.
Variables
PHP variables start with $ and are dynamically typed:
// Variable assignment
$name = "PHP";
$age = 30;
$price = 19.99;
$isActive = true;
$value = null;
// Variable naming
$user_name = "developer"; // snake_case
$userName = "developer"; // camelCase
$MAX_SIZE = 100; // Constants (UPPERCASE)
// Variable variables
$var = "name";
$$var = "PHP"; // $name = "PHP"
// Variable scope
$global = "global";
function test() {
global $global; // Access global variable
$local = "local"; // Local variable
}
Data Types
PHP has several data types:
// Scalar types
$string = "Hello, World!";
$integer = 42;
$float = 3.14;
$boolean = true;
// Compound types
$array = [1, 2, 3];
$object = new stdClass();
// Special types
$null = null;
$resource = fopen("file.txt", "r");
// Type checking
is_string($string); // true
is_int($integer); // true
is_array($array); // true
is_null($null); // true
// Type casting
$number = (int) "42";
$text = (string) 42;
$float = (float) "3.14";
Arrays
PHP arrays are ordered maps (can be arrays or dictionaries):
// Indexed arrays
$fruits = ["apple", "banana", "orange"];
$numbers = array(1, 2, 3, 4, 5);
// Accessing elements
$fruits[0] // "apple"
$fruits[1] // "banana"
$fruits[-1] // "orange" (PHP 7.1+)
// Adding elements
$fruits[] = "grape"; // Add to end
array_push($fruits, "mango"); // Add to end
array_unshift($fruits, "kiwi"); // Add to beginning
// Removing elements
array_pop($fruits); // Remove last
array_shift($fruits); // Remove first
unset($fruits[1]); // Remove at index
// Associative arrays
$person = [
"name" => "John",
"age" => 30,
"city" => "New York"
];
// Accessing associative array
$person["name"] // "John"
$person["age"] // 30
// Array functions
count($fruits); // Get length
in_array("apple", $fruits); // Check if contains
array_search("banana", $fruits); // Find index
array_merge($fruits, ["grape"]); // Merge arrays
array_keys($person); // Get keys
array_values($person); // Get values
Loops
PHP offers several iteration methods:
// For loop
for ($i = 0; $i < 5; $i++) {
echo $i;
}
// Foreach loop (most common for arrays)
$fruits = ["apple", "banana", "orange"];
foreach ($fruits as $fruit) {
echo $fruit;
}
// Foreach with keys
foreach ($fruits as $index => $fruit) {
echo "$index: $fruit";
}
// Foreach with associative arrays
$person = ["name" => "John", "age" => 30];
foreach ($person as $key => $value) {
echo "$key: $value";
}
// While loop
$count = 0;
while ($count < 5) {
echo $count;
$count++;
}
// Do-while loop
do {
echo $count;
$count--;
} while ($count > 0);
// Loop control
foreach ($fruits as $fruit) {
if ($fruit === "banana") {
continue; // Skip to next iteration
}
if ($fruit === "orange") {
break; // Exit loop
}
echo $fruit;
}
Conditionals
Control flow with if/else statements:
// If/else
$age = 20;
if ($age >= 18) {
echo "Adult";
} elseif ($age >= 13) {
echo "Teenager";
} else {
echo "Child";
}
// Ternary operator
$status = $age >= 18 ? "Adult" : "Minor";
// Null coalescing operator (PHP 7+)
$name = $username ?? "Guest";
// Null coalescing assignment (PHP 7.4+)
$data ??= "default";
// Logical operators
if ($age >= 18 && $hasLicense) {
echo "Can drive";
}
if ($isWeekend || $isHoliday) {
echo "Day off";
}
if (!$isComplete) {
echo "Not done yet";
}
// Switch statement
$grade = "B";
switch ($grade) {
case "A":
echo "Excellent";
break;
case "B":
echo "Good";
break;
case "C":
echo "Average";
break;
default:
echo "Needs improvement";
}
Functions
Functions are defined with function:
// Simple function
function greet($name) {
return "Hello, $name!";
}
echo greet("PHP"); // "Hello, PHP!"
// Function with default parameters
function greet($name = "World") {
return "Hello, $name!";
}
// Function with type hints (PHP 7+)
function add(int $x, int $y): int {
return $x + $y;
}
// Function returning multiple values (array)
function get_name_and_age() {
return ["John", 30];
}
list($name, $age) = get_name_and_age();
// Or (PHP 7.1+)
[$name, $age] = get_name_and_age();
// Variable functions
$func = "greet";
echo $func("PHP"); // Calls greet()
// Anonymous functions (closures)
$greet = function($name) {
return "Hello, $name!";
};
echo $greet("PHP");
// Arrow functions (PHP 7.4+)
$add = fn($x, $y) => $x + $y;
echo $add(5, 3); // 8
Classes
PHP supports object-oriented programming:
// Class definition
class Person {
// Properties
public $name;
private $age;
protected $email;
// Constructor
public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}
// Getter method
public function getAge() {
return $this->age;
}
// Setter method
public function setAge($age) {
$this->age = $age;
}
// Instance method
public function introduce() {
return "Hi, I'm {$this->name} and I'm {$this->age} years old";
}
// Static method
public static function create($name, $age) {
return new self($name, $age);
}
}
// Creating objects
$person = new Person("John", 30);
echo $person->introduce();
$person->setAge(31);
// Static method call
$person2 = Person::create("Jane", 25);
Inheritance
PHP supports class inheritance:
// Parent class
class Animal {
protected $name;
public function __construct($name) {
$this->name = $name;
}
public function makeSound() {
echo "Some sound";
}
}
// Child class
class Dog extends Animal {
public function makeSound() {
echo "Woof!";
}
public function wagTail() {
echo "{$this->name} is wagging tail";
}
}
// Using inheritance
$dog = new Dog("Buddy");
$dog->makeSound(); // "Woof!"
$dog->wagTail(); // "Buddy is wagging tail"
String Functions
PHP has many built-in string functions:
$text = "Hello, World!";
// String manipulation
strlen($text); // Get length
strtoupper($text); // "HELLO, WORLD!"
strtolower($text); // "hello, world!"
ucfirst($text); // "Hello, world!"
ucwords($text); // "Hello, World!"
// String searching
strpos($text, "World"); // 7 (position)
str_contains($text, "World"); // true (PHP 8+)
str_replace("World", "PHP", $text); // "Hello, PHP!"
// String extraction
substr($text, 0, 5); // "Hello"
substr($text, 7); // "World!"
// String splitting
explode(", ", $text); // ["Hello", "World!"]
implode(" - ", ["Hello", "World"]); // "Hello - World"
// String formatting
sprintf("Hello, %s!", "PHP"); // "Hello, PHP!"
printf("Hello, %s!", "PHP"); // Prints directly