No history yet

PHP Basics

Getting Started with PHP

PHP is a server-side scripting language. Think of a website like a restaurant. The menu you see is the client-side (your browser), but the chef in the kitchen who prepares your meal is the server-side. PHP is that chef, working behind the scenes to process requests, interact with databases, and create the web page that gets sent back to you.

All PHP code lives inside special tags. The server knows to execute anything between <?php and ?>.

<?php
  // This is a simple PHP script
  echo "Hello, World!";
?>

In this example, echo is a basic command that simply outputs text to the page. The text that follows it, enclosed in quotes, is what will be displayed. Every statement in PHP ends with a semicolon (;). It's like the period at the end of a sentence.

Variables and Data Types

Variables are containers for storing information. In PHP, a variable starts with a dollar sign ($) followed by the variable's name. You can think of them as labeled boxes where you can keep different kinds of data.

<?php
  $greeting = "Welcome to the page!";
  echo $greeting;
?>

PHP supports several types of data. You don't have to tell PHP what type of data a variable will hold; it figures it out automatically. Here are the most common types:

Data TypeDescription
StringA sequence of characters, like text.
IntegerA whole number without a decimal point.
FloatA number with a decimal point.
BooleanRepresents two possible states: true or false.
ArrayHolds multiple values in one variable.
<?php
  // String
  $name = "Alice";

  // Integer
  $age = 30;

  // Float
  $price = 19.99;

  // Boolean
  $is_logged_in = true;

  // Array
  $colors = ["Red", "Green", "Blue"];
  echo $colors[0]; // Outputs "Red"
?>

Making Decisions and Repeating Actions

Control structures are the decision-makers of your code. They allow a script to respond differently to various situations or to repeat an action multiple times.

The most common way to make a decision is with an if statement. It checks if a condition is true and executes a block of code if it is. You can add an else block to run code if the condition is false.

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

  if ($hour < 12) {
    echo "Good morning!";
  } else {
    echo "Good afternoon!";
  }
?>

When you need to repeat a task, you use a loop. A for loop is perfect when you know exactly how many times you want the code to run.

<?php
  // Prints numbers from 1 to 5
  for ($i = 1; $i <= 5; $i++) {
    echo $i . " ";
  }
  // Output: 1 2 3 4 5 
?>

A while loop, on the other hand, continues as long as a certain condition remains true. You use this when you don't know in advance how many times the loop needs to run.

<?php
  $count = 1;
  while ($count <= 3) {
    echo "This is loop iteration #" . $count;
    $count++;
  }
?>

Functions and Error Handling

Functions are reusable blocks of code that perform a specific task. You define a function once and can then call it whenever you need it. This helps keep your code organized and avoids repetition.

Here's how you define and call a simple function:

<?php
  // Define the function
  function greet_user($name) {
    return "Hello, " . $name . "!";
  }

  // Call the function
  $message = greet_user("Bob");
  echo $message; // Outputs "Hello, Bob!"
?>

A variable's scope determines where it can be accessed. Variables declared inside a function are local to that function, meaning they can't be used outside of it. This prevents variables from different parts of your code from interfering with each other.

Mistakes happen, and PHP has ways to handle them. The try...catch block is a clean way to manage errors. You place code that might cause an error inside the try block. If an error occurs, the code inside the catch block is executed, preventing your script from crashing.

<?php
function divide($a, $b) {
  if ($b == 0) {
    // Throw an exception if divisor is zero
    throw new Exception("Division by zero is not allowed.");
  }
  return $a / $b;
}

try {
  echo divide(10, 0);
} catch (Exception $e) {
  // Catch the exception and display a friendly message
  echo "Caught exception: " . $e->getMessage();
}
?>

This lets you handle potential problems gracefully instead of showing a raw error message to the user.

Quiz Questions 1/6

In the context of a website, what is the primary role of a server-side scripting language like PHP?

Quiz Questions 2/6

What is the correct way to begin a variable name in PHP?

With these fundamentals, you have the building blocks to start writing your own simple PHP scripts.