Skip to content

php_examples

  • 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]

  • Declaring and assigning variables ($name = "value";).
  • Variable scope: global vs. local (inside functions).
  • Accessing global variables within functions using the global keyword or the $GLOBALS superglobal 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]

  • Using echo to output one or more strings.
  • Using print to 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]

  • Scalar types: string, int (integer), float (or double), 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]

  • Common string functions: strlen(), str_word_count(), strrev(), strpos() (and stripos for case-insensitive search), str_replace() (and str_ireplace), substr(), strtolower(), strtoupper(), trim().

Read more: [Link to Strings Chapter - Placeholder]

  • 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]

  • 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]

  • if statement.
  • if...else statement.
  • if...elseif...else statement.
  • switch statement (with case, 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]

  • while loop: Checks condition before executing.
  • do...while loop: Executes once, then checks condition.
  • for loop: Initialize, condition, increment.
  • foreach loop: Iterate over arrays and objects (preferred for arrays).

Read more: [Link to Loops Chapter - Placeholder]

  • 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]

  • Indexed arrays (numeric keys, default starting from 0).
  • Associative arrays (string keys).
  • Multidimensional arrays.
  • Short array syntax [] (recommended over array()).
  • Using count() to get the number of elements.
  • Looping through arrays using foreach.

Read more: [Link to Arrays Chapter - Placeholder]

  • 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]

  • $GLOBALS: Access global variables.
  • $_SERVER: Server and execution environment information (headers, paths, script locations).
  • $_REQUEST: Contains $_GET, $_POST, and $_COOKIE data (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]

  • Creating HTML forms (<form method="post" action="...">).
  • Accessing form data using $_GET or $_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]

  • Getting current date/time: date('Y-m-d H:i:s').
  • Working with timestamps: time().
  • Creating dates from strings: strtotime().
  • Using the DateTime object (recommended) for more robust date/time manipulation: new DateTime(), $date->format(), $date->modify(), DateInterval, DateTimeZone.

Read more: [Link to Date/Time Chapter - Placeholder]

  • 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]

  • 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]

  • 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]

  • 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]

  • 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]

  • 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]

  • 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]

  • 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]