No history yet

PHP Basics

The Language of the Web Server

PHP is a scripting language that runs on a web server. Unlike HTML or CSS, which your browser interprets directly, PHP code is processed on the server before a page is sent to you. This allows for dynamic content, like showing a personalized welcome message or pulling the latest blog posts from a database.

To tell the server what part of a file is PHP code, you wrap it in special tags. The most common way is to start with <?php and end with ?>. Every command, or statement, inside these tags must end with a semicolon ;. This tells PHP where one instruction ends and the next begins.

<?php
  // This is a single-line comment
  
  /* 
    This is a multi-line comment.
    It's useful for longer explanations.
  */

  echo "Hello, World!"; // Prints text to the screen
?>

The echo command is one of the most basic and useful in PHP. It simply outputs whatever you give it, which then becomes part of the HTML sent to the user's browser.

Storing Information

To do anything useful, a program needs to store and manage information. In PHP, we use variables for this. A variable is like a labeled container for a piece of data. All variable names in PHP start with a dollar sign \$.

<?php
  💲username = "Alex";
  💲postCount = 42;
  💲isLoggedIn = true;

  echo "Welcome back, ";
  echo 💲username;
?>

Notice that we used the dot . to join the string "Welcome back, " with the value of the \$username variable. This is called concatenation.

PHP supports several fundamental data types:

Data TypeDescriptionExample
stringA sequence of characters"Hello PHP"
integerA whole number (no decimal)100 or -5
floatA number with a decimal point3.14
booleanA true or false valuetrue or false
arrayAn ordered collection of values["apple", "banana"]
nullRepresents a variable with no value yetnull

PHP is a loosely typed language, which means you don't have to declare a variable's type beforehand. PHP automatically figures it out based on the value you assign.

Making Things Happen

Once you have data in variables, you can use operators to manipulate it.

Arithmetic operators are for basic math. You have + (addition), - (subtraction), * (multiplication), / (division), and % (modulus, which gives the remainder of a division).

<?php
  💲price = 10;
  💲tax = 0.5;
  💲total = 💲price + (💲price * 💲tax);
  echo 💲total; // Outputs: 15
?>

Comparison operators let you compare two values. These are the heart of decision-making in code. For example, == checks if two values are equal, while > checks if the first is greater than the second. These expressions always result in a boolean: true or false.

<?php
  💲age = 21;
  💲canDrink = (💲age >= 21); // This will be true

  var_dump(💲canDrink);
?>

A quick tip: == checks if values are equal (e.g., the number 5 and the string "5" are considered equal). A stricter operator, ===, checks if the values and their data types are identical. It's generally safer to use ===.

Logical operators combine conditional statements. The main ones are && (and), || (or), and ! (not).

Controlling the Flow

Control structures let you dictate the flow of your program based on certain conditions. The most common is the if statement.

An if statement runs a block of code only if a condition is true. You can add an else block to run code if the condition is false. For multiple conditions, you can chain them with elseif.

<?php
  💲hour = date('H'); // Gets the current hour (0-23)

  if (💲hour < 12) {
    echo "Good morning!";
  } elseif (💲hour < 18) {
    echo "Good afternoon!";
  } else {
    echo "Good evening!";
  }
?>

When you need to perform an action repeatedly, you use a loop. A for loop is great when you know exactly how many times you want to repeat something. It has three parts: an initializer, a condition, and a counter.

<?php
  // This loop will print the numbers 1 through 5.
  for (💲i = 1; 💲i <= 5; 💲i++) {
    echo 💲i . "\n";
  }
?>

To loop over every item in an array, the foreach loop is often simpler and more readable.

<?php
  💲colors = ["Red", "Green", "Blue"];

  foreach (💲colors as 💲color) {
    echo 💲color . "\n";
  }
?>

Reusable Blocks of Code

As your programs grow, you'll find yourself writing the same logic over and over. Functions solve this by letting you package a block of code under a single name. You can then "call" that function whenever you need it.

Functions can accept inputs, called parameters or arguments, and can also return a value using the return keyword.

<?php
  // Define a function that takes two numbers and returns their sum
  function add(💲num1, 💲num2) {
    return 💲num1 + 💲num2;
  }

  // Call the function and store its result in a variable
  💲sum = add(5, 10);

  echo "The sum is: " . 💲sum; // Outputs: The sum is: 15
?>

This is incredibly powerful. Now, anytime we need to add two numbers, we can just call add() instead of rewriting the logic. This makes code cleaner, more organized, and easier to debug.

Handling Errors Gracefully

Things don't always go as planned. A user might provide bad input, a file might be missing, or a network connection could fail. Good code anticipates these problems.

PHP has several levels of errors. A Notice is a minor issue, like using an undefined variable. A Warning is more serious but doesn't stop the script. A Fatal Error is a critical problem that halts execution immediately.

During development, it's crucial to have error reporting turned on so you can see and fix these issues.

<?php
  // Put these at the top of your script during development
  ini_set('display_errors', 1);
  ini_set('display_startup_errors', 1);
  error_reporting(E_ALL);
?>

For situations where an operation might fail, you can use a try...catch block. You place the risky code in the try block. If an error (called an "exception") occurs, the code in the catch block is executed, allowing you to handle the problem without crashing the application.

<?php
  function divide(💲numerator, 💲denominator) {
    if (💲denominator === 0) {
      // Throwing an exception signals that an error occurred.
      throw new Exception("Cannot divide by zero.");
    }
    return 💲numerator / 💲denominator;
  }

  try {
    echo divide(10, 0);
  } catch (Exception 💲e) {
    // The catch block gracefully handles the error.
    echo "Error: " . 💲e->getMessage();
  }
?>

This prevents the dreaded "division by zero" fatal error and instead shows a user-friendly message.

Quiz Questions 1/6

Where is PHP code executed?

Quiz Questions 2/6

What is the correct operator for joining two strings together in PHP?

These are the fundamental building blocks of PHP. Mastering variables, control structures, and functions will give you a solid base for building powerful and dynamic web applications.