Some practical PHP Examples for Beginners
* Web 2.0 University is supported by it's audience. If you purchase through links on our site, we may earn an affiliate commision.
Learning PHP can be both exciting and rewarding, especially when you start seeing results quickly. To help you get started, this post will provide a series of practical PHP examples tailored for beginners. These examples will cover the basics of PHP, including variables, data types, loops, functions, and more.
1. Hello, World!
Let’s start with the most basic example: printing “Hello, World!” to the screen.
<?php
echo "Hello, World!";
?>
This simple script uses the echo
statement to output text.
2. Variables and Data Types
PHP supports various data types including strings, integers, floats, and booleans.
<?php
// String
$name = "Alice";
echo "Name: " . $name . "<br>";
// Integer
$age = 25;
echo "Age: " . $age . "<br>";
// Float
$height = 5.7;
echo "Height: " . $height . " feet<br>";
// Boolean
$isStudent = true;
echo "Is student: " . ($isStudent ? "Yes" : "No") . "<br>";
?>
3. Arrays
Arrays are used to store multiple values in a single variable.
Indexed Arrays
<?php
$fruits = array("Apple", "Banana", "Cherry");
echo "First fruit: " . $fruits[0] . "<br>";
?>
Associative Arrays
<?php
$person = array("name" => "John", "age" => 30, "city" => "New York");
echo "Name: " . $person["name"] . "<br>";
echo "Age: " . $person["age"] . "<br>";
echo "City: " . $person["city"] . "<br>";
?>
4. Conditionals
Conditional statements are used to perform different actions based on different conditions.
<?php
$temperature = 30;
if ($temperature > 25) {
echo "It's a hot day!<br>";
} elseif ($temperature > 15) {
echo "It's a warm day!<br>";
} else {
echo "It's a cold day!<br>";
}
?>
5. Loops
Loops are used to execute a block of code repeatedly.
For Loop
<?php
for ($i = 0; $i < 5; $i++) {
echo "Number: $i<br>";
}
?>
While Loop
<?php
$i = 0;
while ($i < 5) {
echo "Number: $i<br>";
$i++;
}
?>
6. Functions
Functions are reusable blocks of code that perform a specific task.
Defining and Calling a Function
<?php
function greet($name) {
return "Hello, " . $name . "!";
}
echo greet("Alice") . "<br>";
echo greet("Bob") . "<br>";
?>
Function with Default Parameters
<?php
function greet($name = "Guest") {
return "Hello, " . $name . "!";
}
echo greet() . "<br>";
echo greet("Charlie") . "<br>";
?>
7. Working with Forms
Handling user input through forms is a common task in PHP.
HTML Form
<!DOCTYPE html>
<html>
<body>
<form method="post" action="form_handler.php">
Name: <input type="text" name="name"><br>
Age: <input type="number" name="age"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
PHP Form Handler
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["name"];
$age = $_POST["age"];
echo "Name: " . $name . "<br>";
echo "Age: " . $age . "<br>";
}
?>
8. File Handling
PHP can also be used to read from and write to files.
Writing to a File
<?php
$file = fopen("example.txt", "w");
fwrite($file, "Hello, World!\n");
fwrite($file, "This is a test file.");
fclose($file);
echo "File written successfully.<br>";
?>
Reading from a File
<?php
$file = fopen("example.txt", "r");
while (!feof($file)) {
$line = fgets($file);
echo $line . "<br>";
}
fclose($file);
?>
9. Basic Error Handling
Handling errors gracefully is important for robust applications.
<?php
function divide($numerator, $denominator) {
if ($denominator == 0) {
throw new Exception("Division by zero");
}
return $numerator / $denominator;
}
try {
echo divide(10, 2) . "<br>";
echo divide(10, 0) . "<br>";
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "<br>";
}
?>
10. Connecting to a MySQL Database
Connecting to a database is essential for dynamic web applications.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully<br>";
// Close connection
$conn->close();
?>
Conclusion
These examples cover a wide range of PHP basics, from simple output to database connections. As you continue to practice and explore PHP, you’ll find yourself building more complex and dynamic applications. Remember to keep experimenting and don’t be afraid to make mistakes—it’s all part of the learning process. Happy coding!