php_examples
PHP Code Examples
Section titled “PHP Code Examples”PHP Syntax
Section titled “PHP Syntax”- Outputting text and HTML using
echo. - Single-line (
//or#) and multi-line (/* ... */) comments. - Understanding case sensitivity: Function names, class names, and built-in constructs (like
echo,if,while) are case-insensitive. Variable names ($myVar) are case-sensitive.
Read more: [Link to Syntax Chapter - Placeholder]
PHP Variables
Section titled “PHP Variables”- Declaring and assigning variables (
$name = "value";). - Variable scope: global vs. local (inside functions).
- Accessing global variables within functions using the
globalkeyword or the$GLOBALSsuperglobal array. - Static variables within functions (
static $count = 0;) to retain value between function calls. - Introduction to typed properties (PHP 7.4+) for classes:
public string $name;.
Read more: [Link to Variables Chapter - Placeholder]
PHP Echo and Print
Section titled “PHP Echo and Print”- Using
echoto output one or more strings. - Using
printto output a single string (returns 1). - Embedding variables within double-quoted strings or concatenating with the dot (
.) operator.
Read more: [Link to Echo/Print Chapter - Placeholder]
PHP Data Types
Section titled “PHP Data Types”- Scalar types:
string,int(integer),float(ordouble),bool(boolean). - Compound types:
array,object. - Special types:
resource,null. - Using
var_dump()to inspect variable type and value.
Read more: [Link to Data Types Chapter - Placeholder]
PHP Strings
Section titled “PHP Strings”- Common string functions:
strlen(),str_word_count(),strrev(),strpos()(andstriposfor case-insensitive search),str_replace()(andstr_ireplace),substr(),strtolower(),strtoupper(),trim().
Read more: [Link to Strings Chapter - Placeholder]
PHP Constants
Section titled “PHP Constants”- Defining constants using
define('CONSTANT_NAME', value);(traditionally uppercase). - Defining constants using
const MY_CONSTANT = value;(at top level or within classes). - Constants are inherently global and cannot be redefined.
Read more: [Link to Constants Chapter - Placeholder]
PHP Operators
Section titled “PHP Operators”- Arithmetic:
+,-,*,/,%(modulus),**(exponentiation). - Assignment:
=,+=,-=,*=,/=,%=,.=,??=(null coalescing assignment). - Comparison:
==,===(identical),!=or<>,!==,<,>,<=,>=,<=>(spaceship). - Increment/Decrement:
++$x,$x++,--$x,$x--. - Logical:
and,or,xor,&&,||,!. - String Concatenation:
.. - Array:
+(union),==,===,!=,<>,!==. - Null Coalescing:
??.
Read more: [Link to Operators Chapter - Placeholder]
PHP Conditional Statements
Section titled “PHP Conditional Statements”ifstatement.if...elsestatement.if...elseif...elsestatement.switchstatement (withcase,break,default).- Ternary operator:
condition ? value_if_true : value_if_false;. - Null coalescing operator:
$variable = $maybeNull ?? $default;.
Read more: [Link to If/Else/Switch Chapter - Placeholder]
PHP Loops
Section titled “PHP Loops”whileloop: Checks condition before executing.do...whileloop: Executes once, then checks condition.forloop: Initialize, condition, increment.foreachloop: Iterate over arrays and objects (preferred for arrays).
Read more: [Link to Loops Chapter - Placeholder]
PHP Functions
Section titled “PHP Functions”- Defining functions:
function functionName($arg1, $arg2) { ... }. - Functions with parameters.
- Default argument values:
function greet($name = "Guest") { ... }. - Returning values using
return. - Type hinting for arguments and return types (e.g.,
function add(int $a, int $b): int { ... }). - Arrow functions (PHP 7.4+) for concise closures:
$add = fn($a, $b) => $a + $b;.
Read more: [Link to Functions Chapter - Placeholder]
PHP Arrays
Section titled “PHP Arrays”- Indexed arrays (numeric keys, default starting from 0).
- Associative arrays (string keys).
- Multidimensional arrays.
- Short array syntax
[](recommended overarray()). - Using
count()to get the number of elements. - Looping through arrays using
foreach.
Read more: [Link to Arrays Chapter - Placeholder]
PHP Sorting Arrays
Section titled “PHP Sorting Arrays”- Sort by value:
sort()(ascending),rsort()(descending). - Sort associative arrays by value, preserving keys:
asort()(ascending),arsort()(descending). - Sort associative arrays by key:
ksort()(ascending),krsort()(descending). - Natural order sorting:
natsort(),natcasesort().
Read more: [Link to Sorting Arrays Chapter - Placeholder]
PHP Superglobals
Section titled “PHP Superglobals”$GLOBALS: Access global variables.$_SERVER: Server and execution environment information (headers, paths, script locations).$_REQUEST: Contains$_GET,$_POST, and$_COOKIEdata (use with caution, prefer specific globals).$_POST: Data submitted via HTTP POST method (typically from forms).$_GET: Data submitted via URL query string.$_FILES: Information about uploaded files.$_COOKIE: HTTP Cookies.$_SESSION: Session variables.
Read more: [Link to Superglobals Chapter - Placeholder]
PHP Form Handling & Validation
Section titled “PHP Form Handling & Validation”- Creating HTML forms (
<form method="post" action="...">). - Accessing form data using
$_GETor$_POST. - Importance of validating and sanitizing user input.
- Using filter functions (
filter_var(),filter_input()) for validation (e.g.,FILTER_VALIDATE_EMAIL,FILTER_SANITIZE_STRING). - Preventing Cross-Site Scripting (XSS) using
htmlspecialchars()when outputting user data. - Preventing Cross-Site Request Forgery (CSRF) using tokens.
Read more: [Link to Forms Chapter - Placeholder]
PHP Date and Time
Section titled “PHP Date and Time”- Getting current date/time:
date('Y-m-d H:i:s'). - Working with timestamps:
time(). - Creating dates from strings:
strtotime(). - Using the
DateTimeobject (recommended) for more robust date/time manipulation:new DateTime(),$date->format(),$date->modify(),DateInterval,DateTimeZone.
Read more: [Link to Date/Time Chapter - Placeholder]
PHP Include and Require
Section titled “PHP Include and Require”- Including files:
include 'file.php';(warning on failure),require 'file.php';(fatal error on failure). - Including files only once:
include_once 'file.php';,require_once 'file.php';(preferred for definitions).
Read more: [Link to Include/Require Chapter - Placeholder]
PHP File Handling
Section titled “PHP File Handling”- Reading entire files:
file_get_contents(),readfile(). - Writing to files:
file_put_contents(). - Opening/reading/writing/closing files step-by-step:
fopen(),fread(),fgets(),fwrite(),fclose(),feof(). - Checking file existence:
file_exists().
Read more: [Link to File Handling Chapter - Placeholder]
PHP Cookies
Section titled “PHP Cookies”- Setting cookies:
setcookie('name', 'value', ['expires' => time()+3600, 'path' => '/', 'secure' => true, 'httponly' => true, 'samesite' => 'Lax']);(must be before output). - Reading cookies:
$_COOKIE['name']. - Deleting cookies by setting expiration in the past.
Read more: [Link to Cookies Chapter - Placeholder]
PHP Sessions
Section titled “PHP Sessions”- Starting or resuming a session:
session_start();(must be before output). - Storing session data:
$_SESSION['key'] = 'value';. - Retrieving session data:
$_SESSION['key']. - Destroying a session:
session_unset(); session_destroy();.
Read more: [Link to Sessions Chapter - Placeholder]
PHP Filters
Section titled “PHP Filters”- Using
filter_var()to sanitize or validate data. - Sanitization filters (e.g.,
FILTER_SANITIZE_STRING,FILTER_SANITIZE_EMAIL,FILTER_SANITIZE_URL). - Validation filters (e.g.,
FILTER_VALIDATE_INT,FILTER_VALIDATE_BOOLEAN,FILTER_VALIDATE_EMAIL,FILTER_VALIDATE_IP). - Using
filter_input()to get and filter external variables (INPUT_GET,INPUT_POST, etc.).
Read more: [Link to Filters Chapter - Placeholder]
PHP MySQL Interaction (using PDO/MySQLi)
Section titled “PHP MySQL Interaction (using PDO/MySQLi)”- Connecting to MySQL using PDO or MySQLi.
- Selecting data:
SELECT * FROM table. - Using prepared statements to prevent SQL injection (essential!).
- Fetching results (e.g.,
fetch(),fetchAll()in PDO;fetch_assoc(),fetch_all()in MySQLi). - Inserting, updating, deleting data using prepared statements.
Read more: [Link to MySQL Chapters - Placeholder]
PHP SimpleXML
Section titled “PHP SimpleXML”- Loading XML from a string (
simplexml_load_string()) or file (simplexml_load_file()). - Accessing elements and attributes using object notation (e.g.,
$xml->element->attribute). - Looping through elements.
Read more: [Link to SimpleXML Chapter - Placeholder]
PHP XML Expat Parser
Section titled “PHP XML Expat Parser”- Event-based XML parsing (suitable for large files).
- Creating an XML parser instance (
xml_parser_create()). - Setting up handlers for start/end elements, character data (
xml_set_element_handler(),xml_set_character_data_handler()). - Parsing the XML data (
xml_parse()).
Read more: [Link to XML Expat Chapter - Placeholder]