Sunday, September 29, 2024

Understanding PHP Data Types, A Practical Guide

Even though we have already installed and prepared everything we need to learn and program a programming language, as we prepared to learn the PHP programming language in the previous PHP tutorial post, see here; and since we have printed the famous "Hello World" on the local server web page; the first steps in programming begin with variables. Variables in programming are places in computer memory where data is stored that the program uses for calculation, processing, and manipulation. In the PHP programming language, as in other programming languages; variables are names used to reference places in memory. The easiest way to understand variables is to think of them as memory boxes. But not all boxes are the same. In some, you can put a value that represents an integer, while in others you can put floating-point numbers. There are also boxes in which you can put a set of any characters. To know what value, you can put in a variable, you need to know what data type you have decided to assign to a variable. All programming languages have variables and certain data types.

Most basic variable types are essentially the same or similar. However, some programming languages have more data types while others have fewer. Also, even the same name of a variable type in many programming languages can have different limitations. For example, in the PHP programming language, the float data type has the precision of the double data type, which means that the value of floating-point numbers is much larger than it would be if the data type was float in the C# programming language. Or instead of the char data type in C#, the string type is used in the PHP programming language, while char is a function used to convert an ASCII number to a character. So that you are not confused at the very beginning of learning data types, it is best to concentrate on the data types that the PHP programming language has.

The boss explains the importance of data types in PHP to a new employee

The boss explains the importance of data types in PHP to a new employee

Variables are the fundamental building blocks of every program. They serve as containers for data that can be changed and manipulated throughout the program's execution. In PHP, variables are declared simply by assigning a value to a name. The data type of a variable is determined automatically based on the assigned value. Variable names can include letters, numbers, and underscores, but they must start with a letter or an underscore. Additionally, PHP requires a dollar sign ($) before each variable name to identify it. For example, in this line, we've created a variable named $number and assigned the integer value 10 to it.

$number = 10;

It's essential to choose clear and descriptive variable names to enhance code readability. For instance, if a variable holds the value of the 13th salary, a suitable name would be $thirteenthSalary. Remember that PHP is case-sensitive, meaning $number and $Number are considered different variables. A common convention in PHP is to use camelCase for variable names, as seen in $thirteenthSalary.
Unlike many other programming languages, PHP doesn't require explicit type declarations. When you assign a value to a variable, its data type is inferred automatically, and the necessary memory is allocated.

Basic Data Types in PHP: Simply Explained

Each data type in PHP has its specific use case. Grasping these differences is essential for writing efficient code. PHP offers eight fundamental data types:

integer - for whole numbers

float - for decimal numbers

string - for textual data

boolean - for logical values (true or false)

array - for storing collections of values

object - for creating custom data types

resource - for representing external resources

null - for representing no value

To solidify your understanding, create a PHP script that demonstrates each data type and provides details like the integer range on your system.

Datatypes in PHP programming language

Datatypes in PHP programming language

Simply open your terminal and execute the following commands:

manuel@manuel-virtual-machine:~$ sudo apt-get update

manuel@manuel-virtual-machine:~$ sudo apt-get upgrade

manuel@manuel-virtual-machine:~$ clear

manuel@manuel-virtual-machine:~$ cd /opt/lampp

manuel@manuel-virtual-machine:~$ ls

manuel@manuel-virtual-machine:/opt/lampp$ sudo ./manager-linux-x64.run

When the XAMPP manager window opens, start the Apache Web Server. We do not need MySQL Database in this example. Next, open a new Terminal window and switch to the php_tutorial project folder that we created in the previous lesson. And open Visual Studio Code.

manuel@manuel-virtual-machine:~$ cd /opt/lampp/htdocs/php_tutorial

manuel@manuel-virtual-machine:/opt/lampp /htdocs/php_tutorial$ code .

Click on index.php, then in the code editor panel, modify the following part of the code.

<ul>

    <li><a href="lessons/lesson01.php">

        Lesson 1. - The text printing and comments

    </a></li>

    <li><a href="lessons/lesson02.php">

        Lesson 2. - Variables and data types  

    </a></li>

</ul>

In the lesson’s directory, create a new file and name it lesson02.php. Then start a browser and type localhost/php_tutorial or add the port your local server is running on. If everything is done correctly, you will get the result as in the picture.

The first page of the PHP tutorial presents the content

The first page of the PHP tutorial presents the content

If your result is the same as in the picture, then we are ready to code the code that will show us the variables, data types and finally how the constant is defined. Type the following code in the lesson02.php file in lessons folder.

<?php

    $title = 'Lesson 2';

    require_once '../includes/header.php';

?>

<h2 class="bg-primary text-light text-center py-3">

    Variables and data types

</h2>

<div class="container">

    <?php

        echo "<h2>In PHP, the following data types exist:</h2><br/>";

        echo "  Bool (boolean) <br>

                Integer (int) <br>

                Float (float, double) <br>

                String (string) <br>

                Array (array) <br>

                Object (object) <br>

                Resource (resource) <br>

                Null (null) <br><br/>";       

 

        // This bool type of variable can be true or false

        $boolVariable = true;

        echo "boolean ... True or False <br>";

        echo gettype($boolVariable) . "<br></br>";

        // This integer type of variable can store whole numbers

        $intVariable = 123456789;

        echo " integer... " . $intVariable . "<br>";

        echo gettype($intVariable) . "<br>";

        echo "Maximal value of an integer: " . PHP_INT_MAX . "<br>";

        echo "Minimal value of an integer: " . PHP_INT_MIN . "<br></br>";

        // This float type of variable can store double numbers

        $floatVariable = 1.23456789;

        echo "float -> double ... " . $floatVariable . "<br>";

        echo gettype($floatVariable) . "<br>";

        echo "Maximal value of a double: " . PHP_FLOAT_MAX . "<br>";

        echo "Minimal value of a double: " . PHP_FLOAT_MIN . "<br></br>";

        // This string type of variable can store text

        $stringVariable = "A string data type in PHP can have 128 or 500 or more MB,<br>

                     but it dependents from the server configuration and its memory!";

        echo " string ... " . $stringVariable . "<br>";

        echo gettype($stringVariable) . "<br></br>";

        // This array type of variable can store multiple values

        $arrayVariable = array(1"two"3.0true);

        echo " array ... " . implode(", "$arrayVariable) . "<br>";

        echo gettype($arrayVariable) . "<br></br>";

        // This object type of variable can hold any type of value

        $objectVariable = "An object can hold any type.";

        echo "object -> string ... " . $objectVariable . "<br>";

        echo gettype($objectVariable) . "<br>";

        echo "Make the object... <br>";

        class SomeClass { }  // make a class

        $objectVariable = new SomeClass(); // make an object from the class

        echo gettype($objectVariable) . "<br></br>";

        // This resource type of variable used to represent external resources

        echo "The resource data type in PHP is used to represent external resources <br>

              such as open files, databases, or network connections. <br><br/>";

        // This null type of variable has no value

        $nullVariable = null;

        echo "null ... " . var_export($nullVariabletrue) . "<br>";

        echo gettype($nullVariable) . "<br></br>";

        // a constant

        define("PI"3.14159265359);

        echo " You cannot change constant value after initialization. <br>

               Constant PI = " . PI . " always.";

        echo "</br></br></br></br></br>"

    ?>

</div>

<!-- footer -->

<?php require_once '../includes/footer.php'?>

Open the browser and on the content page, click on Lesson 2. - Variables and data types. A new webpage will open with the following content:

In PHP, the following data types exist:


Bool (boolean)
Integer (int)
Float (float, double)
String (string)
Array (array)
Object (object)
Resource (resource)
Null (null)

boolean ... True or False
boolean

integer... 123456789
integer
Maximal value of an integer: 9223372036854775807
Minimal value of an integer: -9223372036854775808

float -> double ... 1.23456789
double
Maximal value of a double: 1.7976931348623E+308
Minimal value of a double: 2.2250738585072E-308

string ... A string data type in PHP can have 128 or 500 or more MB,
but it dependents from the server configuration and its memory!
string

array ... 1, two, 3, 1
array

object -> string ... An object can hold any type.
string
Make the object...
object

The resource data type in PHP is used to represent external resources
such as open files, databases, or network connections.

null ... NULL
NULL

You cannot change constant value after initialization.
Constant PI = 3.14159265359 always.

The result of executing the lesson02.php file

The result of executing the lesson02.php file

The maximum integer value can vary depending on your system's configuration. For instance, you might see a maximum value of 9,223,372,036,854,775,807, but this can be lower on 32-bit systems. When working with floating-point numbers, be cautious about precision issues. For example, a calculation that results in 1.6 might not be exactly 1.6 due to rounding errors. In PHP, constants are defined using the define function and cannot be changed once set, unlike in Python where variables are often used to represent constants. While not strictly enforced, it's recommended to use uppercase letters and underscores for constant names in PHP. You can see how this PHP web page looks and how it was created in the following video.


PHP - 2. What are Variables, Data Types and Constants?
















 

No comments:

Post a Comment