PHP Reference
PHP Basics
<?php ?> → PHP opening and closing tags.
echo → Outputs text to the browser.
print → Outputs text (similar to echo).
; → Ends a PHP statement.
// comment → Single-line comment.
/* comment */ → Multi-line comment.
Variables
$x = 10; → Declares a variable.
$name = "John"; → String variable.
$isActive = true; → Boolean variable.
$arr = [1,2,3]; → Array variable.
$obj = new stdClass(); → Object variable.
Data Types
string → Text.
int → Integer number.
float → Decimal number.
bool → true or false.
array → List of values.
object → Instance of a class.
null → No value.
Operators
= → Assignment.
+ - * / % → Math operators.
== → Equal (value).
=== → Identical (value and type).
!= / !== → Not equal.
> < >= <= → Comparisons.
&& → AND.
|| → OR.
! → NOT.
. → String concatenation.
Conditionals
if ($x > 5) {} → Runs if condition is true.
else {} → Runs if false.
elseif ($x == 5) {} → Another condition.
switch ($x) {} → Multiple case conditions.
Loops
for ($i=0; $i<10; $i++) {} → Repeats code fixed times.
while ($x < 10) {} → Runs while condition is true.
do {} while ($x < 10); → Runs once then repeats.
foreach ($arr as $value) {} → Loops array values.
foreach ($arr as $k => $v) {} → Loops keys and values.
Functions
function name() {} → Declares a function.
function sum($a,$b) { return $a+$b; } → Function with parameters.
return → Sends value back.
Arrays
$arr = [1,2,3]; → Indexed array.
$arr["name"] = "John"; → Associative array.
count($arr) → Number of items.
array_push($arr,$x) → Add item.
array_pop($arr) → Remove last.
in_array($x,$arr) → Check value exists.
Strings
strlen($str) → String length.
strtolower($str) → Lowercase.
strtoupper($str) → Uppercase.
trim($str) → Remove spaces.
str_replace("a","b",$str) → Replace text.
Forms + Superglobals
$_GET → Data from URL query.
$_POST → Data from form POST.
$_REQUEST → GET + POST.
$_FILES → Uploaded files.
$_SERVER → Server info.
$_SESSION → Session data.
$_COOKIE → Cookies.
File Handling
fopen("file.txt","r") → Open file.
fread($f,100) → Read file.
fwrite($f,"text") → Write file.
fclose($f) → Close file.
file_get_contents("file.txt") → Read whole file.
file_put_contents("file.txt",$data) → Write whole file.
Include + Require
include "file.php"; → Includes file (warning if missing).
require "file.php"; → Includes file (fatal error if missing).
include_once → Include once.
require_once → Require once.
Sessions + Cookies
session_start() → Starts session.
$_SESSION["user"]="John"; → Store session value.
session_destroy() → End session.
setcookie("name","John",time()+3600) → Create cookie.
$_COOKIE["name"] → Read cookie.
Date + Time
date("Y-m-d") → Current date.
time() → Current timestamp.
strtotime("next week") → Convert text to time.
Database (MySQL)
mysqli_connect(host,user,pass,db) → Connect to MySQL.
mysqli_query($conn,$sql) → Run query.
mysqli_fetch_assoc($res) → Fetch row.
mysqli_num_rows($res) → Row count.
mysqli_close($conn) → Close connection.