Special Types

There are 2 special data types in PHP

  1. Resource
  2. Null

Resource Data type:

It refers the external resources like database connection, FTP connection, file pointers, etc. In simple terms, a resource is a special variable which carrying a reference to an external resource.

Example 1

<?php  
    $conn = ftp_connect("127.0.0.1") or die("Could not connect");  
    echo get_resource_type($conn);  
?>  

output

FTP Buffer

Example 2

<?php  
    $conn= ftp_connect("127.0.0.1") or die("could not connect");  
    echo $conn;  
?>  

output

Resource id #2

Example 3

<?php  
    $handle = fopen("tpoint.txt", "r");  
    var_dump($handle);  
    echo "<br>";  
    $conn= ftp_connect("127.0.0.1") or die("could not connect");  
    var_dump($conn);  
?>  

output

resource(3, stream)

resource(4, FTP Buffer)


Null Data Type:

A variable of type Null is a variable without any data. In PHP, null is not a value, and we can consider it as a null variable based on 3 condition.

  1. If the variable is not set with any value.
  2. If the variable is set with a null value.
  3. If the value of the variable is unset.

Example 1

<?php  
       
    $empty=null;  
var_dump($empty);  
?> 

output

null

Example 2

<?php  
        $a1 = " ";  
     var_dump($a1);  
        echo "<br />";  
        $a2 = null;  
        var_dump($a2);  
?>  

output

strring ‘ ‘ (length=1)

null

Example 3

<?php  
    $x = NULL;  
    var_dump($x);  
    echo "<br>";  
    $y = "Hello javatpoint!";  
    $y = NULL;  
    var_dump($y);  
?>  

output

null

null

PHP Switch

PHP switch statement is used to execute one statement from multiple conditions. It works like PHP if-else-if statement.

Syntax

switch(expression){      
case value1:      
 //code to be executed  
 break;  
case value2:      
 //code to be executed  
 break;  
......      
default:       
 code to be executed if all cases are not matched;    
}  

Important points to be noticed about switch case:

  1. The default is an optional statement. Even it is not important, that default must always be the last statement.
  2. There can be only one default in a switch statement. More than one default may lead to a Fatal error.
  3. Each case can have a break statement, which is used to terminate the sequence of statement.
  4. The break statement is optional to use in switch. If break is not used, all the statements will execute after finding matched case value.
  5. PHP allows you to use number, character, string, as well as functions in switch expression.
  6. Nesting of switch statements is allowed, but it makes the program more complex and less readable.
  7. You can use semicolon (;) instead of colon (:). It will not generate any error.

PHP Switch Example

<?php      
$num=20;      
switch($num){      
case 10:      
echo("number is equals to 10");      
break;      
case 20:      
echo("number is equal to 20");      
break;      
case 30:      
echo("number is equal to 30");      
break;      
default:      
echo("number is not equal to 10, 20 or 30");      
}     
?>  

Output:

number is equal to 20

PHP switch statement with character

Program to check Vowel and consonant

We will pass a character in switch expression to check whether it is vowel or constant. If the passed character is A, E, I, O, or U, it will be vowel otherwise consonant.

<?php      
    $ch = 'U';  
    switch ($ch)  
    {     
        case 'a':   
            echo "Given character is vowel";  
            break;  
        case 'e':   
            echo "Given character is vowel";  
            break;  
        case 'i':   
            echo "Given character is vowel";  
            break;  
        case 'o':   
            echo "Given character is vowel";  
            break;    
        case 'u':   
            echo "Given character is vowel";  
            break;  
        case 'A':   
            echo "Given character is vowel";  
            break;  
        case 'E':   
            echo "Given character is vowel";  
            break;  
        case 'I':   
            echo "Given character is vowel";  
            break;  
        case 'O':   
            echo "Given character is vowel";  
            break;  
        case 'U':   
            echo "Given character is vowel";  
            break;  
        default:   
            echo "Given character is consonant";  
            break;  
    }  
?>  

Output:

Given character is vowel

PHP switch statement with String

PHP allows to pass string in switch expression. Let’s see the below example of course duration by passing string in switch case statement.

<?php      
    $ch = "B.Tech";  
    switch ($ch)  
    {     
        case "BCA":   
            echo "BCA is 3 years course";  
            break;  
        case "Bsc":   
            echo "Bsc is 3 years course";  
            break;  
        case "B.Tech":   
            echo "B.Tech is 4 years course";  
            break;  
        case "B.Arch":   
            echo "B.Arch is 5 years course";  
            break;  
        default:   
            echo "Wrong Choice";  
            break;  
    }  
?>

Output:

B.Tech is 4 years course

PHP switch statement is fall-through

PHP switch statement is fall-through. It means it will execute all statements after getting the first match, if break statement is not found.

<?php      
    $ch = 'c';  
    switch ($ch)  
    {     
        case 'a':   
            echo "Choice a";  
            break;  
        case 'b':   
            echo "Choice b";  
            break;  
        case 'c':   
            echo "Choice c";      
            echo "</br>";  
        case 'd':   
            echo "Choice d";  
            echo "</br>";  
        default:   
            echo "case a, b, c, and d is not found";  
    }  
?>  

Output:

Choice c
Choice d
case a, b, c, and d is not found

PHP nested switch statement

Nested switch statement means switch statement inside another switch statement. Sometimes it leads to confusion.

<?php      
    $car = "Hyundai";                   
        $model = "Tucson";    
        switch( $car )    
        {    
            case "Honda":    
                switch( $model )     
                {    
                    case "Amaze":    
                           echo "Honda Amaze price is 5.93 - 9.79 Lakh.";   
                        break;    
                    case "City":    
                           echo "Honda City price is 9.91 - 14.31 Lakh.";    
                        break;     
                }    
                break;    
            case "Renault":    
                switch( $model )     
                {    
                    case "Duster":    
                        echo "Renault Duster price is 9.15 - 14.83 L.";  
                        break;    
                    case "Kwid":    
                           echo "Renault Kwid price is 3.15 - 5.44 L.";  
                        break;    
                }    
                break;    
            case "Hyundai":    
                switch( $model )     
                {    
                    case "Creta":    
                        echo "Hyundai Creta price is 11.42 - 18.73 L.";  
                        break;    
        case "Tucson":    
                           echo "Hyundai Tucson price is 22.39 - 32.07 L.";  
                        break;   
                    case "Xcent":    
                           echo "Hyundai Xcent price is 6.5 - 10.05 L.";  
                        break;    
                }    
                break;     
        }  
?> 

Output:

Hyundai Tucson price is 22.39 - 32.07 L.

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

PHP Data Types: Scalar Types

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

  1. boolean
  2. integer
  3. float
  4. string

PHP Data Types: Compound Types

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

  1. array
  2. object

PHP Data Types: Special Types

There are 2 special data types in PHP.

  1. resource
  2. 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.

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:

  • An integer can be either positive or negative.
  • An integer must not contain decimal point.
  • Integer can be decimal (base 10), octal (base 8), or hexadecimal (base 16).
  • 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

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

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

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

You will learn more about array in later chapters of this tutorial.

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

This is an advanced topic of PHP, which we will discuss later in detail.

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.

This is an advanced topic of PHP, so we will discuss it later in detail with examples.

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:

PHP Variables

In PHP, a variable is declared using a $ sign followed by the variable name. Here, some important points to know about variables:

  • As PHP is a loosely typed language, so we do not need to declare the data types of the variables. It automatically analyzes the values and makes conversions to its correct datatype.
  • After declaring a variable, it can be reused throughout the code.
  • Assignment Operator (=) is used to assign the value to a variable.

Syntax of declaring a variable in PHP is given below:

  1. $variablename=value;  

Rules for declaring PHP variable:

  • A variable must start with a dollar ($) sign, followed by the variable name.
  • It can only contain alpha-numeric character and underscore (A-z, 0-9, _).
  • A variable name must start with a letter or underscore (_) character.
  • A PHP variable name cannot contain spaces.
  • One thing to be kept in mind that the variable name cannot start with a number or special symbols.
  • PHP variables are case-sensitive, so $name and $NAME both are treated as different variable.

PHP Variable: Declaring string, integer, and float

Let’s see the example to store string, integer, and float values in PHP variables.

<?php  
$str="hello string";  
$x=200;  
$y=44.6;  
echo "string is: $str <br/>";  
echo "integer is: $x <br/>";  
echo "float is: $y <br/>";  
?>  

Output:

string is: hello string
integer is: 200
float is: 44.6 

PHP Variable: Sum of two variables

<?php  
$x=5;  
$y=6;  
$z=$x+$y;  
echo $z;  
?>  

Output:

11

PHP Variable: case sensitive

In PHP, variable names are case sensitive. So variable name “color” is different from Color, COLOR, COLor etc.

<?php  
$color="red";  
echo "My car is " . $color . "<br>";  
echo "My house is " . $COLOR . "<br>";  
echo "My boat is " . $coLOR . "<br>";  
?>  

Output:

My car is red
Notice: Undefined variable: COLOR in C:\wamp\www\variable.php on line 4
My house is 
Notice: Undefined variable: coLOR in C:\wamp\www\variable.php on line 5
My boat is 

PHP Variable: Rules

PHP variables must start with letter or underscore only.

PHP variable can’t be start with numbers and special symbols.

<?php  
$a="hello";//letter (valid)  
$_b="hello";//underscore (valid)  
  
echo "$a <br/> $_b";  
?>  

Output:

hello 
hello
<?php  
$4c="hello";//number (invalid)  
$*d="hello";//special symbol (invalid)  
  
echo "$4c <br/> $*d";  
?>  

Output:

Parse error: syntax error, unexpected '4' (T_LNUMBER), expecting variable (T_VARIABLE)
 or '$' in C:\wamp\www\variableinvalid.php on line 2

PHP: Loosely typed language

PHP is a loosely typed language, it means PHP automatically converts the variable to its correct data type.