DEV Community

Cover image for PHP Primer: A Beginner's Guide
Rinesa
Rinesa

Posted on

PHP Primer: A Beginner's Guide

In the world of web development, PHP (Hypertext Preprocessor) is a powerful server-side scripting language that is widely used to create dynamic and interactive web pages. Whether you're new to programming or looking to expand your skills, getting started with PHP can be an exciting journey. In this blog, I'll cover the basics of PHP, from understanding its syntax to handling data types.

1: Introduction to PHP

In first session, let's dive into the fundamentals of PHP.

  • What is PHP? PHP is a server-side scripting language that is embedded in HTML. It is used to create dynamic web pages and interacts with databases.

2: Setting up your environment:

Before you start coding in PHP, you'll need to set up a development environment. You can use tools like XAMPP, MAMP, or WampServer to create a local server environment on your computer. I'm using XAMPP and found it easy to use. First step to set up environment using XAMPP is to install XAMPP and then go at the Local Disk C: on (or wherever you have installed xampp folder) your computer and find xampp folder. Go in and find htdocs folder and inside this folder create your project folder with a new file inside fileName.php (so the file that we want to work with PHP should have the .php extension).

Example:
Path of PHP files
As long as we work just with PHP and we don't use any database, to make the code inside our file work we should Start Apache at the XAMPP control panel as shown in the picture below.

Work with XAMPP

While working with PHP and XAMPP, it's essential to use a reliable code editor to write and manage your PHP files. Visual Studio Code (VSCode): A lightweight yet powerful code editor with built-in support for PHP, syntax highlighting, code completion, and a vast ecosystem of extensions to enhance your development experience.

To be able to run and see the output of our php file code, we have to open a browser and open localhost/foldername/filename as shown below

Run PHP file

3: PHP syntax

PHP code is enclosed within <?php ?> tags. We'll explore basic syntax rules, variables, data types (such as strings, integers, floats, booleans), and basic operators (+, -, *, /, %).

Here is an example of simple syntax of PHP code:

<?php 

//Here goes PHP code
echo "My first blog"; //echo is used to print code that's inside brackets

?>
Enter fullscreen mode Exit fullscreen mode

4: Variables

Variables in PHP start with a dollar sign ($) followed by the variable name (the best practice is that the variable name to be descriptive for the variable content). They are case-sensitive and can store different data types, such as strings, integers, floats, and booleans.

5: Data Types

PHP supports various data types, including strings (text), integers (whole numbers), floats (decimal numbers), booleans (true or false), arrays (ordered collections of data), NULL, object and more.

<?php
    // Define variables
    $name = "John"; // String - Descriptive variable name for the person's name 
    $age = 30; // Integer - Descriptive variable name for the person's age
    $height = 6.1; // Float - Descriptive variable name for the person's height in feet
    $is_student = true; // Boolean - Descriptive variable name indicating whether the person is a student

// Output variables
    echo "Name: $name<br>"; // Outputs: Name: John
    echo "Age: $age<br>"; // Outputs: Age: 30
    echo "Height: $height<br>"; // Outputs: Height: 6.1
    echo "Is Student: " . ($is_student ? "Yes" : "No") . "<br>"; // In this case, if _$is_student_ is true, the expression "Yes" is returned. If _$is_student_ is false, the expression "No" is returned.
?>
Enter fullscreen mode Exit fullscreen mode

Arrays

Arrays are fundamental data structures in PHP that allow you to store and manipulate collections of data. Here is a brief information about types of arrays:

  • Indexed array is a collection of data elements, each identified by an index or a numeric key. Elements in an indexed array are accessed using numerical indices, starting from zero. They are useful for storing lists of items where the order matters.
<?php
    // Indexed Array
    $colors = array("Red", "Green", "Blue");

   // Accessing array elements
    echo "First color: " . $colors[0] . "<br>"; // Outputs: Red
    echo "Second color: " . $colors[1] . "<br>"; // Outputs: Green
    echo "Third color: " . $colors[2] . "<br>"; // Outputs: Blue
?>
Enter fullscreen mode Exit fullscreen mode
  • Associative Array is a collection of key-value pairs, where each key is associated with a specific value. Elements in an associative array are accessed using their keys instead of numerical indices. These are useful for representing data with named attributes or properties.
<?php
// Associative Array
    $person = array("name" => "John", "age" => 30, "city" => "New York");

    // Accessing associative array elements
    echo "Name: " . $person["name"] . "<br>"; // Outputs: John
    echo "Age: " . $person["age"] . "<br>"; // Outputs: 30
    echo "City: " . $person["city"] . "<br>"; // Outputs: New York`
?>
- Multidimensional Array is an array that contains one or more arrays as its elements. Each element of a multidimensional array can be an indexed array, an associative array, or another multidimensional array. These are useful for representing complex data structures, such as matrices or tables.
`
<?php
// Multidimensional Array
    $students = array(
        array("name" => "Alice", "age" => 25),
        array("name" => "Bob", "age" => 28),
        array("name" => "Charlie", "age" => 30)
    );

    // Accessing multidimensional array elements
    echo "Student 1: " . $students[0]["name"] . ", Age: " . $students[0]["age"] . "<br>"; // Outputs: Student 1: Alice, Age: 25
    echo "Student 2: " . $students[1]["name"] . ", Age: " . $students[1]["age"] . "<br>"; // Outputs: Student 2: Bob, Age: 28
    echo "Student 3: " . $students[2]["name"] . ", Age: " . $students[2]["age"] . "<br>"; // Outputs: Student 3: Charlie, Age: 30
?>
Enter fullscreen mode Exit fullscreen mode

6: Basic Operators

PHP supports standard arithmetic operators (+, -, *, /, %), assignment operators (=, +=, -=), comparison operators (==, !=, >, <, >=, <=), and logical operators (&&, ||, !).

<?php
    // Arithmetic Operators
    $num1 = 10;
    $num2 = 5;

    $sum = $num1 + $num2; // Addition
    $difference = $num1 - $num2; // Subtraction
    $product = $num1 * $num2; // Multiplication
    $quotient = $num1 / $num2; // Division
    $remainder = $num1 % $num2; // Modulus

    echo "Sum: $sum<br>"; // Outputs: 15
    echo "Difference: $difference<br>"; // Outputs: 5
    echo "Product: $product<br>"; // Outputs: 50
    echo "Quotient: $quotient<br>"; // Outputs: 2
    echo "Remainder: $remainder<br>"; // Outputs: 0

    // Assignment Operators
    $x = 10;
    $x += 5; // Equivalent to: $x = $x + 5;
    echo "Value of x after addition: $x<br>"; // Outputs: 15

    $y = 20;
    $y -= 8; // Equivalent to: $y = $y - 8;
    echo "Value of y after subtraction: $y<br>"; // Outputs: 12

    // Comparison Operators
    $a = 10;
    $b = 5;

    $isEqual = ($a == $b); // Equal
    $isNotEqual = ($a != $b); // Not Equal
    $isGreaterThan = ($a > $b); // Greater Than
    $isLessThan = ($a < $b); // Less Than
    $isGreaterOrEqual = ($a >= $b); // Greater Than or Equal To
    $isLessOrEqual = ($a <= $b); // Less Than or Equal To

    var_dump($isEqual); // Outputs: bool(false)
    var_dump($isNotEqual); // Outputs: bool(true)
    var_dump($isGreaterThan); // Outputs: bool(true)
    var_dump($isLessThan); // Outputs: bool(false)
    var_dump($isGreaterOrEqual); // Outputs: bool(true)
    var_dump($isLessOrEqual); // Outputs: bool(false)

    // Logical Operators
    $isTrue = true;
    $isFalse = false;

    $logicalAnd = ($isTrue && $isFalse); // Logical AND
    $logicalOr = ($isTrue || $isFalse); // Logical OR
    $logicalNot = !$isTrue; // Logical NOT

    var_dump($logicalAnd); // Outputs: bool(false)
    var_dump($logicalOr); // Outputs: bool(true)
    var_dump($logicalNot); // Outputs: bool(false)
?>
Enter fullscreen mode Exit fullscreen mode

Conclusion:

From understanding the fundamental concepts of PHP to setting up a development environment and exploring key language features such as variables, data types, arrays, and operators, we've covered essential ground.

Top comments (0)