Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Examples in PHP

Examples in PHP

Here are some basic and advanced PHP examples covering various aspects of PHP programming. These examples should help you understand fundamental concepts like variables, loops, functions, arrays, file handling, error handling, and more.

1. Basic PHP Syntax Example

<?php// This is a commentecho "Hello, World!";  // Output text to the screen?>

2. Variables in PHP

<?php$name = "John";$age = 25;echo "My name is $name and I am $age years old.";?>

3. Arrays in PHP

a) Indexed Array

<?php$fruits = array("Apple", "Banana", "Cherry");echo $fruits[0];  // Output: Apple?>

b) Associative Array

<?php$person = array("name" => "John", "age" => 25, "city" => "New York");echo $person["name"];  // Output: John?>

4. Conditional Statements in PHP

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

5. Loops in PHP

a) For Loop

<?phpfor ($i = 1; $i <= 5; $i++) {    echo $i . " ";}?>

b) While Loop

<?php$i = 1;while ($i <= 5) {    echo $i . " ";    $i++;}?>

c) Foreach Loop (for Arrays)

<?php$colors = array("Red", "Green", "Blue");foreach ($colors as $color) {    echo $color . " ";}?>

6. Functions in PHP

<?php// Function without parametersfunction greet() {    echo "Hello, World!";}// Function with parametersfunction greetPerson($name) {    echo "Hello, $name!";}greet();           // Output: Hello, World!greetPerson("John"); // Output: Hello, John!?>

7. Form Handling in PHP (GET Method)

<!-- HTML Form --><form method="GET" action="process.php">    <label for="name">Name:</label>    <input type="text" name="name" id="name">    <input type="submit" value="Submit"></form>
<!-- process.php --><?php$name = $_GET['name'];echo "Hello, $name!";?>

8. File Handling in PHP

a) Reading from a File

<?php$file = fopen("example.txt", "r");if ($file) {    while (($line = fgets($file)) !== false) {        echo $line . "<br>";    }    fclose($file);} else {    echo "Unable to open file.";}?>

b) Writing to a File

<?php$file = fopen("example.txt", "w");if ($file) {    fwrite($file, "Hello, World!");    fclose($file);    echo "Data written to file.";} else {    echo "Unable to open file.";}?>

9. Handling Errors in PHP

a) Custom Error Handler

<?php// Custom error handler functionfunction customError($errno, $errstr) {    echo "Error [$errno]: $errstr";}// Set the custom error handlerset_error_handler("customError");// Trigger an errorecho $undefined_variable;?>

b) Handling Exceptions

<?php// Custom exception classclass MyException extends Exception {    public function errorMessage() {        return "Error occurred: " . $this->getMessage();    }}try {    // Throw an exception    throw new MyException("Something went wrong!", 1);} catch (MyException $e) {    echo $e->errorMessage();}?>

10. Sessions in PHP

<?php// Start the sessionsession_start();// Set session variables$_SESSION["username"] = "John";$_SESSION["email"] = "john@example.com";// Access session variablesecho "Welcome " . $_SESSION["username"];?>

11. Cookies in PHP

a) Setting a Cookie

<?php// Set a cookie for 1 daysetcookie("user", "John", time() + 86400, "/");  // 86400 = 1 day// Check if the cookie is setif (isset($_COOKIE["user"])) {    echo "Hello, " . $_COOKIE["user"];} else {    echo "Cookie is not set.";}?>

12. Date and Time in PHP

<?php// Get the current date and timeecho date("Y-m-d H:i:s");  // Output: 2025-04-23 14:30:00// Get a specific date formatecho date("l, F j, Y");  // Output: Wednesday, April 23, 2025?>

13. Database Connection and Querying in PHP (MySQL)

<?php$servername = "localhost";$username = "root";$password = "";$dbname = "test_db";// Create connection$conn = new mysqli($servername, $username, $password, $dbname);// Check connectionif ($conn->connect_error) {    die("Connection failed: " . $conn->connect_error);}// Select data from the database$sql = "SELECT id, name FROM users";$result = $conn->query($sql);if ($result->num_rows > 0) {    // Output data of each row    while ($row = $result->fetch_assoc()) {        echo "id: " . $row["id"] . " - Name: " . $row["name"] . "<br>";    }} else {    echo "0 results";}// Close the connection$conn->close();?>

14. Using include and require

a) Include a File

<?phpinclude 'header.php';?>

b) Require a File

<?phprequire 'config.php';?>
  • include will still execute the script even if the file is missing (with a warning).

  • require will stop the execution if the file is missing (with a fatal error).


15. Redirecting a Page in PHP

<?phpheader("Location: https://www.example.com");exit();?>

This redirects the user to a different page.


Conclusion

These PHP examples demonstrate a wide range of concepts, from basic syntax to more advanced features like handling errors, working with files, and interacting with databases. Depending on your needs, you can expand on these examples to build more complex PHP applications. Let me know if you'd like further explanation on any of these examples!

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql