"Welcome to our PHP 101 blog, where we demystify the world of web development. "

Friday, January 19, 2024

PHP Datatypes

 

PHP Data Types

PHP data types are used to hold different types of data or values. PHP supports 8 primitive data types that can be categorized further in 3 types:

1.      Scalar Types (predefined)

2.      Compound Types (user-defined)

3.      Special Types       

Scalar Types

It holds only single value. There are 4 scalar data types in PHP.

                    i.            boolean

                  ii.            integer      

                iii.            float

                iv.            string

Compound Types

It can hold multiple values. There are 2 compound data types in PHP.

                    i.            array

                  ii.            object

Special Types

There are 2 special data types:

                    i.            resource

                  ii.            NULL

PHP Boolean

Booleans are the simplest data type works like switch. It holds only two values: TRUE (1) or FALSE (0). It is often used with conditional statements. If the condition is correct, it returns TRUE otherwise FALSE.

Example: 

<?php   

    if (TRUE)  

        echo "This condition is TRUE.";  

    if (FALSE)  

        echo "This condition is FALSE.";  

?>  

 

 

 

Output:

This condition is TRUE.

Explanation Of CODE:

·         The first if statement:

if (TRUE)

echo "This condition is TRUE.";

In this case, the condition inside the parentheses is TRUE. Since TRUE is always true in PHP, the code inside the corresponding block will be executed. Therefore, the string "This condition is TRUE." will be echoed.

·         The second if statement:

if (FALSE)

echo "This condition is FALSE.";

In this case, the condition inside the parentheses is FALSE. Since FALSE is always false in PHP, the code inside the corresponding block will not be executed. Therefore, the string "This condition is FALSE." will not be echoed.

So, when you run this code, only the output of the first if statement will be displayed:

This condition is TRUE.

 

PHP Integer

Integer means numeric data with a negative or positive sign. It holds only whole numbers, i.e., numbers without fractional part or decimal points.

Rules for integer:

1.      An integer can be either positive or negative.

2.      An integer must not contain decimal point.

3.      Integer can be decimal (base 10), octal (base 8), or hexadecimal (base 16).

4.      The range of an integer must be lie between 2,147,483,648 and 2,147,483,647 i.e., -2^31 to 2^31.

Example:

<?php   

    $dec1 = 34;  

    $oct1 = 0243;  

    $hexa1 = 0x45;  

    echo "Decimal number: " .$dec1. "</br>";  

    echo "Octal number: " .$oct1. "</br>";  

    echo "HexaDecimal number: " .$hexa1. "</br>";  

?>  

 

 Output:       

Decimal number: 34
Octal number: 163
HexaDecimal number: 69

Explanation Of CODE:

             ·         $dec1 = 34;: This variable is assigned the decimal value 34.

·         $oct1 = 0243;: This variable is assigned the octal value 243. Octal numbers in PHP start with a leading zero.

·         $hexa1 = 0x45;: This variable is assigned the hexadecimal value 45. Hexadecimal numbers in PHP start with "0x" or "0X".

·         The echo statements then display these values with corresponding labels:

·         echo "Decimal number: " . $dec1 . "</br>";: Outputs "Decimal number: 34" on the webpage.

·         echo "Octal number: " . $oct1 . "</br>";: Outputs "Octal number: 243" on the webpage.

·         echo "Hexadecimal number: " . $hexa1 . "</br>";: Outputs "Hexadecimal number: 69" on the webpage.

·         When you run this code, you will see the representation of the decimal, octal, and hexadecimal numbers on the webpage.

PHP Float

A floating-point number is a number with a decimal point. Unlike integer, it can hold numbers with a fractional or decimal point, including a negative or positive sign.

Example:

<?php   

    $n1 = 19.34;  

    $n2 = 54.472;  

    $sum = $n1 + $n2;  

    echo "Addition of floating numbers: " .$sum;  

?>                        

 

 Output:

Addition of floating numbers: 73.812

Explanation of CODE:

·         $n1 = 19.34;:

This variable is assigned the floating-point value 19.34.

·         $n2 = 54.472;:

This variable is assigned the floating-point value 54.472.

·         $sum = $n1 + $n2;:

This line calculates the sum of the two floating-point numbers and stores the result in the variable $sum.

·         echo "Addition of floating numbers: " . $sum;:

The echo statement outputs the text "Addition of floating numbers: " concatenated with the value of $sum.

This will display the result of the addition on the webpage.

 

PHP String

A string is a non-numeric data type. It holds letters or any alphabets, numbers, and even special characters.

String values must be enclosed either within single quotes or in double quotes. But both are treated differently. To clarify this, see the example below:

Example:

<?php   

    $company = "Javatpoint";  

    //both single and double quote statements will treat different  

    echo "Hello $company";  

    echo "</br>";  

    echo 'Hello $company';  

?>                    

Output:

Hello Javatpoint
Hello $company

Explanation of CODE:

·         $company = "Javatpoint";:

This line assigns the string "Javatpoint" to the variable $company.

·         echo "Hello $company";:

In this line, the double-quoted string allows the variable $company to be directly interpolated within the string. This means that the value of the variable is inserted into the string when it is echoed. The output of this line will be: Hello Javatpoint.

·         echo "</br>";:

This line outputs an HTML line break (<br>), creating a new line.

·         echo 'Hello $company';:

In this line, the single-quoted string treats everything between the single quotes as a literal string. The variable $company is not interpolated, and the output will be: Hello $company.

PHP Array

An array is a compound data type. It can store multiple values of same data type in a single variable.

Example:       

<?php   

    $bikes = array ("Royal Enfield""Yamaha""KTM");  

    var_dump($bikes);   //the var_dump() function returns the datatype and values  

    echo "</br>";  

    echo "Array Element1: $bikes[0] </br>";  

    echo "Array Element2: $bikes[1] </br>";  

    echo "Array Element3: $bikes[2] </br>";  

?>  

Output:

array(3) { [0]=> string(13) "Royal Enfield" [1]=> string(6) "Yamaha" [2]=> string(3) "KTM" }
Array Element1: Royal Enfield
Array Element2: Yamaha
Array Element3: KTM

Explanation of CODE

·         $bikes = array("Royal Enfield", "Yamaha", "KTM");:

This line creates an array named $bikes with three elements, each representing a brand of motorcycle.

·         var_dump($bikes);:

The var_dump() function is used to display the datatype and values of the array. The output shows that it's an array with three elements, and it provides information about the type and length of each string element.

·         echo "</br>";:

This line outputs an HTML line break (<br>), creating a new line in the display.

·         echo "Array Element1: $bikes[0] </br>";, echo "Array Element2: $bikes[1] </br>";, echo "Array Element3: $bikes[2] </br>";:

These lines access individual elements of the array and echo them. The output shows the values of each element.

 

PHP object

Objects are the instances of user-defined classes that can store both values and functions. They must be explicitly declared.

Example:

<?php   

     class bike {  

          function model() {  

               $model_name = "Royal Enfield";  

               echo "Bike Model: " .$model_name;  

             }  

     }               

     $obj = new bike();  

     $obj -> model();  

?>  

Output:

Bike Model: Royal Enfield

Explaination Of CODE:

·         class bike { ... }:

This declares a class named bike. Inside the class, there is a method called model().

·         function model() { ... }:

This is the model() method of the bike class. It contains a local variable $model_name set to "Royal Enfield" and echoes the text "Bike Model: " concatenated with the value of $model_name.

·         $obj = new bike();:

This line creates an instance of the bike class and assigns it to the variable $obj. Now, $obj is an object of the bike class.

·         $obj->model();:

This line calls the model() method on the $obj object. As a result, "Bike Model: Royal Enfield" will be echoed to the screen.

PHP Resource

Resources are not the exact data type in PHP. Basically, these are used to store some function calls or references to external PHP resources. For example - a database call. It is an external resource.

Example:

<?php

// Open a file for reading

$fileHandle = fopen("example.txt", "r");

// Check if the file handle is a valid resource

if (is_resource($fileHandle)) {

    echo "File handle is a valid resource.<br>";

    // Reading and displaying the content of the file

    $content = fread($fileHandle, filesize("example.txt"));

    echo "File content: $content<br>";

    // Close the file handle

    fclose($fileHandle);

} else {

    echo "Failed to open the file.<br>";

}

?>

Output:

·         suppose your file example.txt  contains the following content:

Hello, this is an example file.

In this case, the output of the program would be:

File handle is a valid resource.

File content: Hello, this is an example file.

·         If "example.txt" doesn't exist or cannot be opened for some reason, the output might be:

Failed to open the file.

Explanation Of CODE:

·         fopen("example.txt", "r");:

This function opens the file "example.txt" for reading and returns a file handle resource. The resource is stored in the variable $fileHandle.

·         is_resource($fileHandle):

This function checks if $fileHandle is a valid resource. If it is, the code proceeds to read the file content.

·         fread($fileHandle, filesize("example.txt")):

This function reads the content of the file associated with the file handle ($fileHandle). The file size is determined using filesize("example.txt").

·         fclose($fileHandle);:

This function closes the file handle when it's no longer needed.

PHP Null:

Null is a special data type that has only one value: NULL. There is a convention of writing it in capital letters as it is case sensitive.

The special type of data type NULL defined a variable with no value.

Example:

<?php   

    $nl = NULL;  

    echo $nl;   //it will not give any output  

?>  

Output:

No visible output

Explanation of CODE:

$nl = NULL;:

This line initializes a variable $nl and assigns it the value NULL. In PHP, NULL is a special constant representing a variable with no value or no type.

echo $nl;:

The echo statement is used to output the value of the variable $nl. However, since the value is NULL, it will not produce any visible output.

No comments:

Post a Comment

Pages

SoraTemplates

Best Free and Premium Blogger Templates Provider.

Buy This Template