PHP Examples



Here’s a collection of common PHP examples that demonstrate various functionalities and features. Each example includes a brief description, code snippet, and explanation.

1. Hello World

Description: A simple PHP script that outputs "Hello, World!".

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

2. Variables and Data Types

Description: Demonstrating variable declaration and different data types in PHP.

<?php
$name = "John"; // String
$age = 30;      // Integer
$height = 5.9;  // Float
$is_student = true; // Boolean

echo "Name: $name, Age: $age, Height: $height, Student: $is_student";
?>

3. Arrays

Description: Creating and accessing elements in an associative array.

<?php
$colors = array("red" => "FF0000", "green" => "00FF00", "blue" => "0000FF");

echo "Red color code is: " . $colors["red"];
?>

4. Conditional Statements

Description: Using if...else to check a condition.

<?php
$score = 75;

if ($score >= 60) {
    echo "You passed!";
} else {
    echo "You failed!";
}
?>

5. Loops

Description: A for loop that outputs numbers from 1 to 5.

<?php
for ($i = 1; $i <= 5; $i++) {
    echo "Number: $i<br>";
}
?>

6. Functions

Description: Creating and calling a simple function.

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

echo greet("Alice");
?>

7. File Handling

Description: Writing to a file and reading from it.

<?php
// Writing to a file
file_put_contents("example.txt", "Hello, File!");

// Reading from the file
$content = file_get_contents("example.txt");
echo $content;
?>

8. Form Handling

Description: Handling form submission and displaying submitted data.

<!DOCTYPE html>
<html>
<body>

<form method="post">
    Name: <input type="text" name="name">
    <input type="submit">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = htmlspecialchars($_POST['name']);
    echo "Hello, $name!";
}
?>

</body>
</html>

9. Sessions

Description: Starting a session and storing user data.

<?php
session_start();
$_SESSION['username'] = 'JohnDoe';

echo "Session variable is set to: " . $_SESSION['username'];
?>

10. MySQL Database Connection

Description: Connecting to a MySQL database using mysqli.

<?php
$host = 'localhost';
$db = 'mydatabase';
$user = 'root';
$pass = '';

$conn = new mysqli($host, $user, $pass, $db);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

echo "Connected successfully";
$conn->close();
?>

11. Prepared Statements

Description: Using prepared statements to insert data into a database safely.

<?php
$conn = new mysqli($host, $user, $pass, $db);
$stmt = $conn->prepare("INSERT INTO users (username, email) VALUES (?, ?)");
$stmt->bind_param("ss", $username, $email);

$username = "newuser";
$email = "newuser@example.com";
$stmt->execute();

echo "New record created successfully";
$stmt->close();
$conn->close();
?>

12. JSON Encoding and Decoding

Description: Encoding an array to JSON and decoding JSON back to PHP array.

<?php
$data = array("name" => "John", "age" => 30);
$jsonData = json_encode($data);

echo $jsonData; // Output: {"name":"John","age":30}

$decodedData = json_decode($jsonData, true);
echo "Name: " . $decodedData['name'];
?>

13. Exception Handling

Description: Using try-catch to handle exceptions.

<?php
try {
    $value = 10 / 0; // This will throw an exception
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}
?>

14. OOP Basics

Description: Creating a simple class and object.

<?php
class Car {
    public $color;
    
    function __construct($color) {
        $this->color = $color;
    }
    
    function getColor() {
        return $this->color;
    }
}

$myCar = new Car("red");
echo "My car color is: " . $myCar->getColor();
?>