beginner
Step 1 of 16
Introduction to PHP
PHP Programming
Introduction to PHP
PHP (Hypertext Preprocessor) is one of the most widely used server-side programming languages on the web. Created by Rasmus Lerdorf in 1994, PHP powers approximately 77% of all websites with a known server-side programming language, including major platforms like WordPress, Facebook (originally), Wikipedia, and millions of other sites. PHP is specifically designed for web development and can be embedded directly into HTML, making it intuitive for creating dynamic web pages. Modern PHP (8.x) has evolved significantly with strong typing, attributes, enums, fibers, and performance improvements that make it a mature and powerful language.
Setting Up PHP
# Install PHP on macOS
brew install php
# Install PHP on Ubuntu/Debian
sudo apt install php php-cli php-mbstring php-xml php-curl
# Check PHP version
php -v
# PHP 8.3.x (cli)
# Start built-in development server
php -S localhost:8000
# Run a PHP script from command line
php script.php
Your First PHP Script
<?php
// PHP code is enclosed in <?php ... ?> tags
// Output to browser or terminal
echo "Hello, World!
";
print("Hello again!
");
// Variables start with $
$name = "Developer";
$age = 25;
echo "Welcome, $name! You are $age years old.
";
// PHP can be embedded in HTML
?>
<!DOCTYPE html>
<html>
<body>
<h1>Welcome, <?php echo $name; ?>!</h1>
<p>Today is <?php echo date('Y-m-d'); ?></p>
</body>
</html>
PHP Data Types
<?php
// Strings
$greeting = "Hello";
$name = 'World';
$combined = "{$greeting}, {$name}!"; // Variable interpolation (double quotes only)
// Integers and Floats
$count = 42;
$price = 19.99;
// Booleans
$is_active = true;
$is_deleted = false;
// Null
$result = null;
// Arrays (indexed)
$fruits = ["apple", "banana", "cherry"];
echo $fruits[0]; // "apple"
// Arrays (associative — like dictionaries)
$person = [
"name" => "Alice",
"age" => 30,
"city" => "New York"
];
echo $person["name"]; // "Alice"
// Type checking
echo gettype($count); // "integer"
echo is_string($name); // true
var_dump($person); // Detailed type + value info
// Type casting
$str_num = "42";
$num = (int)$str_num; // 42
$float = (float)"3.14"; // 3.14
?>
Pro tip: Usevar_dump()instead ofechoorprint_r()for debugging, as it shows both the type and value of variables. For a cleaner output in the browser, wrap it in<pre>tags:echo "<pre>"; var_dump($data); echo "</pre>";
Key Takeaways
- PHP is a server-side language that powers the majority of the web and integrates seamlessly with HTML.
- Variables start with
$, and PHP supports strings, integers, floats, booleans, null, and arrays. - Use double quotes for string interpolation (
"Hello, $name") and single quotes for literal strings. - PHP 8.x includes modern features like named arguments, match expressions, enums, and typed properties.
- The built-in server (
php -S localhost:8000) is perfect for development without installing Apache or Nginx.