Introduction to PHP Basics and Syntax

Oct 12, 2024

PHP Overview

  • PHP is a server-side scripting language used for creating dynamic websites.
  • Despite claims of being obsolete, PHP powers approximately 78% of all websites, including popular platforms like Facebook, Wikipedia, and Flipkart.

History of PHP

  • Originally stood for Personal Home Page; now it's a recursive acronym for PHP Hypertext Preprocessor.
  • Development began in 1993 by Rasmus Laerdorf to manage his personal website.

Running PHP Code

  • PHP can be embedded directly within HTML files by changing the file extension from .html to .php.
  • Raw PHP code can be viewed in a web browser if not run on a server.
  • Use XAMPP to execute PHP files:
    • Install XAMPP on major OS (including Linux).
    • Start the Apache server from the XAMPP control panel.
    • Create a folder in the htdocs directory for your PHP code.
    • Access the file via localhost/foldername/filename.php.

Basic PHP Syntax

  • PHP code is written within <?php ... ?> tags.
  • Use echo to display output; example: echo "PHP is great";
  • Comments:
    • Single-line: // or #
    • Multi-line: /* ... */

Variables

  • Declared using $VARIABLE_NAME = value;
  • Case-sensitive (e.g., $var vs $Var).
  • All elements except variables are case-insensitive.

Data Types

  • PHP has 8 primary data types:
    • Integer: Whole numbers
    • Float: Decimal numbers
    • String: Sequence of characters (single or double quotes)
    • Boolean: Represents true/false (1 for true)
    • Array: Can store multiple values of different types.
      • Indexed Arrays: Accessed by numerical index (0, 1, 2...)
      • Associative Arrays: Key-value pairs.
    • Object: Supports Object-Oriented Programming (OOP) using class and new keywords.
    • Resource: Refers to external resources (e.g., files).
    • NULL: Represents a variable with no value.

Control Statements

Conditional Statements

  • If Statement:
    • Syntax: if (condition) {...} else {...}
  • Switch Statement:
    • Compares variable with multiple values; includes case and default.

Loops

  • While Loop: Executes code while the condition is true.
  • Do While Loop: Executes code at least once before checking the condition.
  • For Loop: Runs code a specific number of times; syntax includes initialization, condition, and increment.
  • For Each Loop: Iterates over arrays easily.

Functions

  • Define functions using function functionName() {...}.
  • Call functions by their name followed by parentheses. Function parameters can be used to pass values.