Skip to content

Quick Start

Overview

Now that your environment is set up, let's write your first PHP script and understand the basic principles of how PHP works. This chapter will get you coding immediately with practical examples.

Your First PHP Script

Hello World

Create a file named hello.php:

php
<?php
echo "Hello, World!";
?>

Run it:

bash
php hello.php

Output:

Hello, World!

PHP in HTML

Create hello_web.php:

php
<!DOCTYPE html>
<html>
<head>
    <title>My First PHP Page</title>
</head>
<body>
    <h1><?php echo "Welcome to PHP!"; ?></h1>
    <p>Today is <?php echo date('Y-m-d H:i:s'); ?></p>
</body>
</html>

Run with built-in server:

bash
php -S localhost:8000

Visit http://localhost:8000/hello_web.php

PHP Tags

php
<?php
// Your PHP code here
?>
php
<?
// Avoid using short tags
?>

Echo Tags (PHP 5.4+)

php
<h1><?= "Hello, World!" ?></h1>
<!-- Equivalent to: -->
<h1><?php echo "Hello, World!"; ?></h1>

Basic Syntax Rules

Statements and Semicolons

php
<?php
echo "First statement";  // Semicolon required
echo "Second statement"; // Semicolon required
?>

Case Sensitivity

php
<?php
// Variables are case-sensitive
$name = "John";
$Name = "Jane";  // Different variable

// Functions are case-insensitive
echo "Hello";    // Works
ECHO "Hello";    // Also works
Echo "Hello";    // Also works
?>

Comments

php
<?php
// Single-line comment

# Another single-line comment

/*
Multi-line comment
can span multiple lines
*/

/**
 * Documentation comment
 * Used for generating documentation
 */
?>

Variables and Basic Data Types

Variables

php
<?php
$message = "Hello, PHP!";
$number = 42;
$price = 19.99;
$isActive = true;

echo $message;
echo $number;
?>

Variable Rules

  • Must start with $ sign
  • Name must begin with a letter or underscore
  • Can contain letters, numbers, and underscores
  • Case-sensitive
php
<?php
$validName = "OK";
$_validName = "OK";
$valid_name = "OK";
$validName2 = "OK";

// Invalid names:
// $2invalid = "Error";  // Cannot start with number
// $invalid-name = "Error";  // Cannot contain hyphen
?>

String Operations

Creating Strings

php
<?php
$singleQuoted = 'Hello, World!';
$doubleQuoted = "Hello, World!";

// Variable interpolation (only in double quotes)
$name = "Alice";
$greeting = "Hello, $name!";  // "Hello, Alice!"
$greeting2 = 'Hello, $name!'; // "Hello, $name!" (literal)
?>

String Concatenation

php
<?php
$firstName = "John";
$lastName = "Doe";

// Using dot operator
$fullName = $firstName . " " . $lastName;

// Using double quotes
$fullName = "$firstName $lastName";

echo $fullName; // "John Doe"
?>

Common String Functions

php
<?php
$text = "Hello, World!";

echo strlen($text);           // 13 (length)
echo strtoupper($text);       // "HELLO, WORLD!"
echo strtolower($text);       // "hello, world!"
echo substr($text, 0, 5);     // "Hello"
echo str_replace("World", "PHP", $text); // "Hello, PHP!"
?>

Number Operations

Basic Arithmetic

php
<?php
$a = 10;
$b = 3;

echo $a + $b;  // 13 (addition)
echo $a - $b;  // 7  (subtraction)
echo $a * $b;  // 30 (multiplication)
echo $a / $b;  // 3.333... (division)
echo $a % $b;  // 1  (modulo)
echo $a ** $b; // 1000 (exponentiation, PHP 5.6+)
?>

Number Functions

php
<?php
$number = 3.7;

echo round($number);     // 4
echo floor($number);     // 3
echo ceil($number);      // 4
echo abs(-5);           // 5
echo max(1, 5, 3);      // 5
echo min(1, 5, 3);      // 1
echo rand(1, 10);       // Random number between 1 and 9
?>

Arrays (Quick Introduction)

Indexed Arrays

php
<?php
$fruits = array("apple", "banana", "orange");
// Or using short syntax (PHP 5.4+)
$fruits = ["apple", "banana", "orange"];

echo $fruits[0]; // "apple"
echo $fruits[1]; // "banana"
?>

Associative Arrays

php
<?php
$person = [
    "name" => "John",
    "age" => 30,
    "city" => "New York"
];

echo $person["name"]; // "John"
echo $person["age"];  // 30
?>

Control Structures (Quick Preview)

If Statements

php
<?php
$age = 18;

if ($age >= 18) {
    echo "You are an adult";
} else {
    echo "You are a minor";
}
?>

Loops

php
<?php
// For loop
for ($i = 1; $i <= 5; $i++) {
    echo "Number: $i\n";
}

// Foreach loop
$colors = ["red", "green", "blue"];
foreach ($colors as $color) {
    echo "Color: $color\n";
}
?>

Functions (Quick Preview)

Built-in Functions

php
<?php
echo date("Y-m-d");        // Current date
echo time();               // Current timestamp
echo phpversion();         // PHP version
echo gettype($variable);   // Variable type
?>

Custom Functions

php
<?php
function greet($name) {
    return "Hello, " . $name . "!";
}

echo greet("Alice"); // "Hello, Alice!"
?>

Practical Examples

Simple Calculator

php
<?php
function calculate($num1, $num2, $operation) {
    switch ($operation) {
        case '+':
            return $num1 + $num2;
        case '-':
            return $num1 - $num2;
        case '*':
            return $num1 * $num2;
        case '/':
            return $num2 != 0 ? $num1 / $num2 : "Error: Division by zero";
        default:
            return "Error: Invalid operation";
    }
}

echo calculate(10, 5, '+'); // 15
echo calculate(10, 5, '/'); // 2
?>

Dynamic Web Page

php
<!DOCTYPE html>
<html>
<head>
    <title>Dynamic Page</title>
</head>
<body>
    <h1>Welcome!</h1>
    
    <?php
    $currentHour = date('H');
    
    if ($currentHour < 12) {
        $greeting = "Good morning!";
    } elseif ($currentHour < 18) {
        $greeting = "Good afternoon!";
    } else {
        $greeting = "Good evening!";
    }
    ?>
    
    <p><?= $greeting ?></p>
    <p>Current time: <?= date('H:i:s') ?></p>
    
    <h2>Random Fact</h2>
    <?php
    $facts = [
        "PHP stands for PHP: Hypertext Preprocessor",
        "PHP was created by Rasmus Lerdorf in 1994",
        "Over 79% of websites use PHP",
        "WordPress is built with PHP"
    ];
    
    $randomFact = $facts[array_rand($facts)];
    ?>
    <p><em><?= $randomFact ?></em></p>
</body>
</html>

Common Beginner Mistakes

1. Forgetting PHP Tags

php
<!-- Wrong -->
echo "Hello";

<!-- Correct -->
<?php echo "Hello"; ?>

2. Missing Semicolons

php
<?php
// Wrong
echo "Hello"
echo "World"

// Correct
echo "Hello";
echo "World";
?>

3. Variable Scope Issues

php
<?php
$globalVar = "I'm global";

function test() {
    // This won't work - $globalVar is not accessible here
    // echo $globalVar;
    
    // Use global keyword or pass as parameter
    global $globalVar;
    echo $globalVar;
}
?>

4. Mixing Single and Double Quotes

php
<?php
$name = "John";

// Wrong - single quotes don't parse variables
echo 'Hello, $name!'; // Output: Hello, $name!

// Correct
echo "Hello, $name!"; // Output: Hello, John!
// Or
echo 'Hello, ' . $name . '!'; // Output: Hello, John!
?>

Development Tips

1. Use Error Reporting

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

2. Use var_dump() for Debugging

php
<?php
$data = ["name" => "John", "age" => 30];
var_dump($data); // Shows detailed variable information
?>

3. Keep Code Organized

php
<?php
// Good practice: separate logic from presentation
$pageTitle = "My Website";
$currentYear = date('Y');
?>
<!DOCTYPE html>
<html>
<head>
    <title><?= $pageTitle ?></title>
</head>
<body>
    <footer>&copy; <?= $currentYear ?> My Company</footer>
</body>
</html>

Next Steps

You've now written your first PHP scripts and learned the basic syntax. In the next chapter Basic Syntax, we'll dive deeper into PHP's syntax rules and conventions.

Practice Exercises

  1. Create a PHP script that displays your name, age, and favorite color
  2. Build a simple "About Me" web page using PHP variables
  3. Create a script that calculates and displays the area of a rectangle
  4. Make a dynamic page that shows different content based on the time of day

Try these exercises to reinforce your understanding before moving on!

Content is for learning and research only.