Author: Saim Khalid

  • Integers

    Integers in PHP

    Integer is one of the built-in scalar types in PHP. A whole number, without a decimal point in the literal, is of the type “int” in PHP. An integer can be represented in decimal (base 10), hexadecimal (base 16), octal (base 8) or binary (base 2) notation.

    To use octal notation, a number is preceded with “0o” or “0O” (PHP 8.1.0 and earlier). From PHP 8.1.0 onward, a number prefixed with “0” and without a decimal point is an octal number.

    To use hexadecimal notation, precede the number with “0x”. To use binary notation, precede the number with “0b”.

    Syntax to Declare Integers in PHP

    Here is syntax for declaring Integers in PHP Programming language −

    // Positive integer$num1=10;// Negative integer$num2=-5;// Zero$num3=0;

    Rules for Integers

    There are some rules for integers −

    • An integer must have at least one digit.
    • An integer cannot contain a decimal point.
    • An integer can be either positive or negative.
    • There are three ways to define integers: decimal (base 10), hexadecimal (base 16 – prefixed with 0x), octal (base 8 – preceded with 0), and binary (base 2 – prefixed with 0b).

    Integer Range in PHP

    The size of an integer depends on the system, with 32-bit systems having a range of -2,147,483,648 to 2,147,483,647, and 64-bit systems having a larger range.

    For checking the maximum and minimum integer values in PHP you can use −

    <?php
       // Maximum integer value   
       echo PHP_INT_MAX;  
       
       echo "\n";
    
       // Minimum integer value
       echo PHP_INT_MIN;  
    ?>

    Output

    It will generate the following result −

    9223372036854775807
    -9223372036854775808
    

    Example

    Take a look at this following example −

    <?php
       $a = 1234; 
       echo "1234 is an Integer in decimal notation: $a\n";
    
       $b = 0123; 
       echo "0o123 is an integer in Octal notation: $b\n";
    
       $c = 0x1A; 
       echo "0xaA is an integer in Hexadecimal notation: $c\n";
    
       $d = 0b1111;
       echo "0b1111 is an integer in binary notation: $d";
    ?>

    Output

    It will produce the below output −

    1234 is an Integer in decimal notation: 1234
    0o123 is an integer in Octal notation: 83
    0xaA is an integer in Hexadecimal notation: 26
    0b1111 is an integer in binary notation: 15
    

    PHP 7.4.0 onwards, integer literals may contain underscores (_) as separators between digits, for better readability of literals. These underscores are removed by PHP’s scanner.

    Example

    Take a look at this following example −

    <?php
       $a = 1_234_567; 
       echo "1_234_567 is an Integer with _ as separator: $a";
    ?>

    Output

    It will generate the following output −

    1_234_567 is an Integer with _ as separator: 1234567
    

    PHP does not support unsigned ints. The size of an int is platform dependent. On 32 bit systems, the maximum value is about two billion. 64-bit platforms usually have a maximum value of about 9E18.

    int size can be determined using the constant PHP_INT_SIZE, maximum value using the constant PHP_INT_MAX, and minimum value using the constant PHP_INT_MIN.

    If an integer number happens to be beyond the bounds of the int type, or any operation results in a number beyond the bounds of the int type, it will be interpreted as a float instead.

    Example

    Take a look at this following example −

    <?php
       $x = 1000000;
       $y =  50000000000000 * $x;
       var_dump($y); 
    ?>

    Output

    This will bring about the following output −

    float(5.0E+19)
    

    PHP doesn’t have any operator for integer division. Hence, a division operation between an integer and a float always results in float. To obtain integral division, you may use the intval() built-in function.

    Example

    Take a look at this following example −

    <?php
       $x = 10;
       $y = 3.5;
       $z = $x/$y;
       var_dump ($z);
       $z = intdiv($x, $y);
       var_dump ($z);
    ?>

    Output

    The output of this PHP code is −

    float(2.857142857142857)
    int(3)
    

    Arithmetic Operations with Integers

    So with the integers you can perform math operations like addition, subtraction, multiplication and division. Here is the examples for showing the usage −

    <?php
       $a = 10;
       $b = 5;
    
       // Addition 
       echo "Addition = ".$a + $b;  
       echo "\n";
    
       // Subtraction
       echo "Subtraction = ".$a - $b;  
       echo "\n";
    
       // Multiplication 
       echo "Multiplication = ".$a * $b;  
       echo "\n";
    
       // Division 
       echo "Division = ".$a / $b;
    ?>

    Output

    This will generate the below result −

    Addition = 15
    Subtraction = 5
    Multiplication = 50
    Division = 2
    

    PHP Functions to Check an Integer

    PHP provides the below functions or methods to check that the type of a variable is an integer or not −

    • is_int(): It is used to check if a given variable is an integer.
    • is_integer() – alias of is_int(): It is another name (alias) for is_int(). It works the same way as is_int().
    • is_long() – alias of is_int(): It is also an alias for is_int(). It is rarely used but works the same way.
  • Boolean

    Boolean Type in PHP

    In PHP, “bool” is a basic data type. It informs if something is true or not. A Boolean can only have two values: true or false. True and false in PHP can be written in several ways, such as true, TRUE, or True, and they all mean the same thing. Boolean values help you make decisions in your code.

    For example, you can tell if something is correct (true) or incorrect (false). This can be used in conditions, loops and other PHP programming areas to control how the code executes based on true or false values.

    The following is the list of topics discussed in this chapter −

    • Syntax to declare a Boolean Type
    • Boolean Values in PHP Conditions
    • Boolean Conversion in PHP
    • Boolean Operators in PHP
    • Strict Comparison with Boolean
    • Boolean in PHP Functions
    • Boolean Arrays in PHP
    • Boolean Constants in PHP
    • Practical Applications of Boolean

    Syntax to declare a Boolean Type

    Here is the way you can declare a variable of bool type as follows −

    // Boolean true$bool1=true;// Boolean true$bool2=True;// Boolean false$bool3=FALSE;// Boolean false$bool4=false;

    Example

    Logical operators (<, >, ==, !=, etc.) return Boolean values.

    <?php
       $gender="Male";
       var_dump ($gender=="Male");
    ?>

    It will produce the following output −

    bool(true)
    

    Example

    Here is the simple example in which the variable $is_sunny is set to true. The if statement checks if $is_sunny variable is true. As it is true so it will print ‘It is a sunny day!’.

    <?php
       $is_sunny = true;
    
       if ($is_sunny) {
    
      echo "It is a sunny day!";
    } else {
      echo "It is not sunny today.";
    } ?>

    Here is the output of the above program −

    It is a sunny day!
    

    Boolean Values in PHP Conditions

    Boolean values are used in the construction of control statements such as if, while, for and foreach. The behaviour of these statements depends on the true/false value returned by the Boolean operators.

    The following conditional statement uses the Bool value returned by the expression in the parenthesis in front of the if keyword −

    <?php
       $mark=60;
    
       if ($mark > 50)
    
      echo "pass";
    else
      echo "fail";
    ?>

    Following is the output of the above program −

    pass
    

    Boolean Conversion in PHP

    Use the (bool) casting operator to convert a value to bool. When a value is used in a logical context it will be automatically interpreted as a value of type bool.

    A non-zero number is considered as true, only 0 (+0.0 or -0.0) is false. Non-empty string represents true, empty string “” is equivalent to false. Similarly, an empty array returns false.

    Example

    Take a look at this following example −

    <?php
       $a = 10;
       echo "$a: ";
       var_dump((bool)$a);
    
       $a = 0;
       echo "$a: ";
       var_dump((bool)$a);
    
       $a = "Hello";
       echo "$a: ";
       var_dump((bool)$a);
    
       $a = "";
       echo "$a: ";
       var_dump((bool)$a);
    
       $a = array();
       echo "$a: ";
       var_dump((bool)$a);
    ?>

    It will produce the following output −

    10: bool(true)
    0: bool(false)
    Hello: bool(true)
    : bool(false)
    Array: bool(false)
    

    Boolean Operators in PHP

    Logical operators in PHP are symbols or words which perform logical operations on values that are either TRUE or FALSE. They are used to check logical conditions and manipulate boolean values.

    <?php
       $a = true;
       $b = false;
    
       // AND operator
       var_dump($a && $b);  
    
       // OR operator
       var_dump($a || $b);  
    
       // NOT operator
       var_dump(!$a); 
    ?>

    It will generate the following outcome −

    bool(false)
    bool(true)
    bool(false)
    

    Strict Comparison with Booleans

    A strict comparison with Boolean is the use of the strict equality operator (===) to compare values, that not only the values themselves but also their data types are equal and always returning a Boolean result of true or false.

    <?php
       $val1 = true;
       $val2 = 1;
    
       var_dump($val1 == $val2);  
       var_dump($val1 === $val2); 
    ?>

    It will produce the below output −

    bool(true)
    bool(false)
    

    Boolean in PHP Functions

    PHP also provide some built in functions for boolean values. These functions are is_bool(), empty(), isset() etc. So we are showing the example of is_bool() which is used to check that the value is boolean or not and isset() which is used to check the value is set or not.

    <?php
       $is_bool = is_bool(true);  
       var_dump($is_bool);
    
       // false if $name is not defined
       $isset = isset($name);  
       var_dump($isset);
    ?>

    It will produce the following output −

    bool(true)
    bool(false)
    

    Boolean Arrays in PHP

    Let us see if there is an array which contains boolean values and display the items of array using a loop.

    <?php
       $boolArray = [true, false, true];
       foreach ($boolArray as $value) {
    
      var_dump($value);
    } ?>

    It will generate the below output −

    bool(true)
    bool(false)
    bool(true)
    

    Boolean Constants in PHP

    In PHP, Boolean Constants are used to make logics and conditions. PHP offers two types of Boolean Constants true and false. Let us see an example below −

    <?php
       const STATUS = true;
       if (STATUS) {
    
      echo "Status is active!";
    } ?>

    It will produce the following output −

    Status is active!
    

    Practical Applications of Booleans

    Real-world example where Boolean values are used, like user authentication, form validation and feature toggles. Here is an example where we will get the status of the user is logged in or not.

    <?php
       $user_logged_in = true;
       if ($user_logged_in) {
    
      echo "Welcome, User!";
    } ?>

    Here is the output the above code −

    Welcome, User!

  • Strings

    A string is a sequence of characters, like ‘PHP supports string operations.’ A string in PHP as an array of bytes and an integer indicating the length of the buffer. In PHP, a character is the same as a byte. This means that PHP only supports a 256-character set, and hence does not offer native Unicode support.

    PHP supports single quoted as well as double quoted string formation. Both the representations ‘this is a simple string’ as well as “this is a simple string” are valid. PHP also has Heredoc and Newdoc representations of string data type.

    Here is the list of covered concepts in this chapter −

    • Single-Quoted String
    • Double-Quoted String
    • Escaping Characters in PHP
    • String Concatenation Operator
    • The strlen() Function
    • The strpos() Function

    Single-Quoted String

    A sequence of characters enclosed in single quotes (the character ‘) is a string.

    $str='this is a simple string';

    Example

    If you want to include a literal single quote, escape it with a backslash (\).

    <?php
       $str = 'This is a \'simple\' string';
       echo $str;
    ?>

    It will give you the following output −

    This is a 'simple' string  
    

    Example

    To specify a literal backslash, double it (\\).

    <?php
       $str = 'The command C:\\*.* will delete all files.';
       echo $str;
    ?>

    Here is its output −

    The command C:\*.* will delete all files.
    

    Example

    The escape sequences such as “\r” or “\n” will be treated literally and their special meaning will not be interpreted. The variables too will not be expanded if they appear in a single quoted string.

    <?php
       $str = 'This will not expand: \n a newline';
       echo $str . PHP_EOL;
       $x=100;
       $str = 'Value of x = $x';
       echo $str;
    ?>

    It will produce the following output −

    This will not expand: \n a newline
    Value of x = $x
    

    Double-Quoted String

    A sequence of characters enclosed in double-quotes (” “) is another string representation.

    $str="this is a simple string";

    Single-quoted and double-quoted strings are equivalent except for their treatment of escape sequences. PHP will interpret certain escape sequences for special characters. For example, “\r” and “\n”.

    SequenceMeaning
    \nlinefeed (LF or 0x0A (10) in ASCII)
    \rcarriage return (CR or 0x0D (13) in ASCII)
    \thorizontal tab (HT or 0x09 (9) in ASCII)
    \vvertical tab (VT or 0x0B (11) in ASCII)
    \eescape (ESC or 0x1B (27) in ASCII)
    \fform feed (FF or 0x0C (12) in ASCII)
    \\backslash
    \$dollar sign
    \”double-quote

    Escaping Characters in PHP

    PHP supports escaping an Octal and a hexadecimal number to its ASCII character. For example, the ASCII character for P is 80 in decimal. 80 in decimal to Octal is 120. Similarly, 80 in decimal to hexadecimal is 50.

    To escape an octal character, prefix it with “\”; and to escape a hexadecimal character, prefix it with “\x”.

    <?php
       $str = "\120\110\120";
       echo "PHP with Octal: ". $str;
       echo PHP_EOL;
    
       $str = "\x50\x48\x50";
       echo "PHP with Hexadecimal: ". $str;
    ?>

    Check the output −

    PHP with Octal: PHP
    PHP with Hexadecimal: PHP
    

    As in single quoted strings, escaping any other character will result in the backslash being printed too. The most important feature of double-quoted strings is the fact that variable names will be expanded.

    Example

    A double-quoted string in PHP expands the variable names (PHP variables are prefixed with $ symbol). To actually represent a “$” symbol in a PHP string, escape it by prefixing with the “\” character.

    <?php
       $price = 200;
       echo "Price = \$ $price";
    ?>

    You will get the following output −

    Price = $ 200
    

    String Concatenation Operator

    To concatenate two string variables together, PHP uses the dot (.) operator −

    <?php
       $string1="Hello World";
       $string2="1234";
    
       echo $string1 . " " . $string2;
    ?>

    Here, you will get the following output −

    Hello World 1234
    

    In the above example, we used the concatenation operator twice. This is because we had to insert a third string. Between the two string variables, we added a string with a single character, an empty space, to separate the two variables.

    The standard library of PHP includes many functions for string processing. They can be found at PHP’s official documentation (https://www.php.net/manual/en/ref.strings.php).

    The strlen() Function

    The strlen() function returns the string’s length, which is the number of characters before the first null termination character. This is less than the amount of RAM allocated to the string, which can be measured with the sizeof operator.

    Syntax

    Here is the syntax for the strlen() function −

    strlen($str);

    It takes single parameter which is the string we need to check the length for.

    Example

    Let’s find the length of our string “Hello world!” −

    <?php
       echo strlen("Hello world!");
    ?>

    It will produce the following output −

    12
    

    The length of a string is often used in loops or other functions, when it is important to know when the string ends (that is, in a loop, we would want to stop the loop after the last character in the string).

    The strpos() Function

    The strpos() function is used to search for a string or character within a string.

    • If a match is found in the string, this function will return the position of the first match.
    • If no match is found, it will return FALSE.

    Syntax

    Here is the syntax for the strpos() function −

    strpos($str,$find,$start)

    This function accepts two parameters. The first parameter is the string to search, and the second parameter is the substring to search for.

    Example

    Let’s see if we can find the string “world” in our string −

    <?php
       echo strpos("Hello world!","world");
    ?>

    It will produce the following output −

    6
    

    As you can see, the position of the string “world” in our string is “6”. The reason that it is “6”, and not “7”, is that the first position in the string is “0”, and not “1”.

  • Type Juggling

    PHP is a dynamically typed language, which means the type of a variable can be changed based on the value sent to it at runtime. This automatic type conversion in PHP is called type juggling.

    In languages like C, C++ and Java, a variable’s type must be defined before it can be used and it can only hold values of that type. But PHP handles type conversions automatically, allowing variables to carry a wide range of values without the need for explicit type declaration.

    No Explicit Type Declaration in PHP

    Explicit type declaration of a variable is neither needed nor supported in PHP. Hence the type of PHP variable is decided by the value assigned to it, and not the other way around. Further, when a variable is assigned a value of different type, its type too changes.

    Example 1

    Look at the following variable assignment in PHP.

    <?php
       $var = "Hello";
       echo "The variable \$var is of " . gettype($var) . " type" .PHP_EOL;
    
       $var = 10;
       echo "The variable \$var is of " . gettype($var) . " type" .PHP_EOL;
    
       $var = true;
       echo "The variable \$var is of " . gettype($var) . " type" .PHP_EOL;
    
       $var = [1,2,3,4];
       echo "The variable \$var is of " . gettype($var) . " type" .PHP_EOL;
    ?>

    Output

    It will produce the following output −

    The variable $var is of string type
    The variable $var is of integer type
    The variable $var is of boolean type
    The variable $var is of array type
    

    You can see the type of “$var” changes dynamically as per the value assigned to it. This feature of PHP is called “type juggling”.

    Example 2

    Type juggling also takes place during calculation of expression. In this example, a string variable containing digits is automatically converted to integer for evaluation of addition expression.

    <?php
       $var1=100;
       $var2="100";
       $var3=$var1+$var2;
       var_dump($var3);
    ?>

    Output

    Here is its output −

    int(200)
    

    Example 3

    If a string starts with digits, trailing non-numeric characters if any, are ignored while performing the calculation. However, PHP parser issues a notice as shown below −

    <?php
       $var1=100;
       $var2="100 days";
       $var3=$var1+$var2;
       var_dump($var3);
    ?>

    Output

    You will get the following result −

    int(200)
    
    PHP Warning:  A non-numeric value encountered in /home/cg/root/53040/main.php on line 4
    

    Type Casting vs Type Juggling

    In PHP, type juggling is the automatic changing of a variable’s data type when necessary. For example, adding an integer value to a variable makes it an integer. PHP handles this automatically, with no user action required.

    On the other hand, type casting occurs when a user actively changes a variable’s data type. This means that the user decides what type the variable should be and then converts it using a specific method.

    In simple terms, PHP automatically performs type juggling, while the programmer performs type casting.

    Example

    Type casting forces a variable to be used as a certain type. The following script shows an example of different type cast operators −

    <?php
       $var1=100;
       $var2=(boolean)$var1;
       $var3=(string)$var1;
       $var4=(array)$var1;
       $var5=(object)$var1;
       var_dump($var2, $var3, $var4, $var5);
    ?>

    Output

    It will generate the following outcome −

    bool(true)
    string(3) "100"
    array(1) {
      [0]=>
      int(100)
    }
    object(stdClass)#1 (1) {
      ["scalar"]=>
      int(100)
    }
    

    Example

    Casting a variable to a string can also be done by enclosing in double quoted string −

    <?php
       $var1=100.50;
       $var2=(string)$var1;
       $var3="$var1";
       var_dump($var2, $var3);
    ?>

    Output

    Here, you will get the following result −

    string(5) "100.5"
    string(5) "100.5"
    

    PHP Type Juggling Vulnerability

    PHP Type Juggling vulnerability occurs when PHP automatically changes data types, which can lead to security vulnerabilities. When comparing values, PHP tries to transform them so they match, which can be dangerous if not done correctly.

    For example, see the below code in PHP −

    // It will be true as PHP ignores non-numeric part."123abc"==123

    This means that if your code checks a password or security token using == (double equals), PHP can view two different responses as the same because of to type juggling. Hackers can use this to get unauthorized access to your computer.

    How to resolve This?

    To avoid this issue we need to always use strict comparison (===), which checks both value and type −

    // This is false as the type is different."123abc"===123

    This makes sure that PHP does not change data types and makes your code more secure.

  • Type Casting

    The term “Type Casting” refers to conversion of one type of data to another. Since PHP is a weakly typed language, the parser coerces certain data types into others while performing certain operations. For example, a string having digits is converted to integer if it is one of the operands involved in the addition operation.

    Table of Content

    • Implicit Type Casting
    • Type Casting Operators
    • Casting to Integer
    • Casting to Float Type
    • Casting to String Type
    • Casting to Bool Type
    • Type Casting Functions

    Implicit Type Casting

    Here is an example of coercive or implicit type casting −

    <?php
       $a = 10;
       $b = '20';
       $c = $a+$b;
       echo "c = " . $c;
    ?>

    In this case, $b is a string variable, cast into an integer to enable addition. It will produce the following output −

    c = 30
    

    Let’s take another example. Here, an integer variable $a is converted to a string so that it is concatenated with a string variable.

    <?php
       $a = 10;
       $b = '20';
       $c = $a.$b;
       echo "c = " . $c;
    ?>

    It will produce the following output −

    c = 1020
    

    In addition to such coercive type conversion, there are other ways to explicitly cast one type of data to other. You can use PHPs type casting operators or type casting functions for this purpose.

    Type Casting Operators

    To convert an expression of one type to another, you need to put the data type of the latter in parenthesis before the expression.

    $var=(type)expr;

    Some of the type casting operators in PHP are −

    • (int) or (integer) casts to an integer
    • (bool) or (boolean) casts to a boolean
    • (float) or (double) or (real) casts to a float
    • (string) casts to a string
    • (array) casts to an array
    • (object) casts to an object

    Casting to Integer

    You can easily convert a float value to an integer. Take a look at the following example −

    <?php
       $a = 9.99;
       $b = (int)$a;
       var_dump($b);
    ?>

    It will produce the following output −

    int(9)
    

    Note that the float value is not rounded to the nearest integer; instead it just returns the integer part.

    String to Integer Conversion

    The (int) operator also coverts a string to integer. The conversion is straightforward if the string consists of just digits.

    <?php
       $a = "99";
       $b = (int)$a;
       var_dump($b);
    ?>

    Here, you will get the following output −

    int(99)
    

    Even if the string contains a floating point number, the (int) operator returns just the integer part.

    Now let’s take another example to understand a special case. If the string is alphanumeric, casting with (int) works differently.

    • If the string starts with digits followed by non-numeric characters, only the initial digits are considered.
    • If the string starts with non-numeric characters and the digits are in the middle, the csting operator returns “0”.

    Take a look at the following example −

    <?php
       $a = "10 Rs.";
       $b = (int)$a;
       var_dump($b);
    
       $a = "$100";
       $b = (int)$a;
       var_dump($b);
    ?>

    It will produce the following output −

    int(10)
    int(0)
    

    Casting to Float Type

    You can use either the (float) or (double) casting operator to explicitly convert a variable or expression to a float.

    <?php
       $a = 100;
       $b = (double)$a;
       var_dump($b);
    ?>

    It will produce the following output −

    float(100)
    

    A string containing any valid numeric representation may be cast to a float type by using a casting operator.

    <?php
       $a = "100";
       $b = (double)$a;
       var_dump($b);
    
       $a = "9.99";
       $b = (float)$a;
       var_dump($b);
    ?>

    Here, you will get the following output −

    float(100)
    float(9.99)
    

    The string gets converted to float even when it embeds a scientific notation of float. Take a look at the following example −

    <?php
       $a = "1.23E01";
       $b = (double)$a;
       var_dump($b);
       $a = "5.5E-5";
       $b = (float)$a;
       var_dump($b);
    ?>

    It will produce the following output −

    float(12.3)
    float(5.5E-5)
    

    All the non-numeric characters after the floating point numbers are ignored. Similarly, the string converts to “0” if it starts with any non-numeric character. See the following example −

    <?php
       $a = "295.95 only";
       $b = (double)$a;
       var_dump($b);
    
       $a = "$2.50";
       $b = (float)$a;
       var_dump($b);
    ?>

    It will produce the following output −

    float(295.95)
    float(0)
    

    Casting to String Type

    By using a casting operator, any expression evaluating to a floating-point or integer may be cast to a string type. Few examples are given below −

    <?php
       $a = 100;
       $b = (string)$a;
       var_dump($b);
    
       $x = 55.50;
       $y = (string)$x;
       var_dump($y);
    ?>

    You will get the following output −

    string(3) "100"
    string(4) "55.5"
    

    Casting to Bool Type

    Any non-zero number, either integer or float, is cast to true with (bool) operator. An expression evaluating to “0” returns false. A string is always cast to true.

    Take a look at the following example −

    <?php
       $a = 100;
       $b = (bool)$a;
    
       $x = 0;
       $y = (bool)$x;
    
       $m = "Hello";
       $n = (bool)$m;
    
       var_dump($b);
       var_dump($y);
       var_dump($n);
    ?>

    It will produce the following output −

    bool(true)
    bool(false)
    bool(true)
    

    Type Casting Functions

    PHP includes the following built-in functions for performing type casting −

    • intval()
    • floatval()
    • strval()

    Let’s discuss these built-in functions in detail.

    The intval() Function

    This function gets the integer value of a variable.

    intval(mixed$value,int$base=10):int

    The $base parameter is 10 by default, which means the value is converted to decimal number.

    • If the value is a float, the intval() function returns an integer, discarding the fractional part.
    • A string representation of a number returns a corresponding integer, discarding the fractional part, if any.
    • If the value is a string with a valid octal number and the base is 8, the intval() function returns a corresponding octal number.

    When the base is “0”, the conversion of value takes place on the basis of character prefix.

    • If the value starts with 0X or 0x, a hexadecimal number is returned.
    • If the value starts with 0B or 0b, a binary number is returned
    • If the value starts with 0, the function returns an octal number.

    The intval() function returns 1 for true, 0 for false Boolean values.

    Example

    The following example shows how the intval() function works −

    <?php
       echo intval(42). PHP_EOL;                     
       echo intval(4.2). PHP_EOL;                    
       echo intval('42') . PHP_EOL;                   
    
       echo intval(042) . PHP_EOL;         # 0ctal number 
       echo intval('042', 0) . PHP_EOL;    # 0ctal number
       echo intval('42', 8) . PHP_EOL;     # octal  
    
       echo intval(0x1A) . PHP_EOL;        # Hexadecimal              
       echo intval('0x1A', 16) . PHP_EOL;  # Hexadecimal           
       echo intval('0x1A', 0) . PHP_EOL;   # Hexadecimal         
    
       echo intval(false) . PHP_EOL;                  
       echo intval(true) . PHP_EOL; 
    ?>

    It will produce the following output −

    42
    4
    42
    34
    34
    34
    26
    26
    26
    0
    1
    

    The floatval() Function

    The floatval() function gets the float value of an expression.

    floatval(mixed$value):float

    The value may be any scalar variable. String with non-numeric characters returns “0”. A string with a numeric representation or with the starting substring with a numeric representation returns the corresponding number. The following example shows how the floatval() function works −

    <?php
       echo floatval(42). PHP_EOL;                     
       echo floatval(4.2). PHP_EOL;                    
       echo floatval('42') . PHP_EOL;                   
    
       echo floatval('99.90 Rs') . PHP_EOL;      
       echo floatval('$100.50') . PHP_EOL;      
       echo floatval('ABC123!@#') . PHP_EOL; 
    
       echo (true) . PHP_EOL; ;
       echo (false) . PHP_EOL; 
    ?>

    It will produce the following output −

    42
    4.2
    42
    99.9
    0
    0
    1
    

    The doubleval() function is an alias of floatval() function, and hence returns similar results.

    The strval() Function

    The strval() function gets the string value of a variable. This function performs no formatting on the returned value.

    strval(mixed$value):string

    The value that is being converted to a string may be any scalar type, null, or an object that implements the __toString() method. Take a look at the following example −

    <?php
       echo strval(42). PHP_EOL;                     
       echo strval(4.2). PHP_EOL;                    
       echo strval(4.2E5) . PHP_EOL;                   
    
       echo strval(NULL) . PHP_EOL;      
    
       echo (true) . PHP_EOL; 
       echo (false) . PHP_EOL; 
    ?>

    It will produce the following output −

    42
    4.2
    420000
    
    1
    

    The following example defines a class that implements the _toString() method.

    <?php
       class myclass {
    
      public function __toString() {
         return __CLASS__;
      }
    } echo strval(new myclass); ?>

    Here, you will get the following output −

    myclass

  • Data Types

    The term “Data Types” refers to the classification of data in distinct categories in PHP. Data types define the types of data that a variable can store.

    PHP supports a wide range of data types, like string, integer, float etc. Data types make it easier to store and handle information in programs. Knowing data types is important for writing correct and clear code.

    List of Data Types

    PHP has a total of eight data types that we use to construct our variables −

    • Integers − Whole numbers, without a decimal point, like 4195.
    • Doubles − Floating-point numbers like 3.14159 or 49.1.
    • Booleans − Have only two possible values, either true or false.
    • NULL − Special type that only has one value: NULL.
    • Strings − Sequences of characters, like ‘PHP supports string operations.’
    • Arrays − Named and indexed collections of other values.
    • Objects − Instances of programmer-defined classes, which can package up both other kinds of values and functions that are specific to the class.
    • Resources − Special variables that hold references to resources external to PHP (such as database connections).

    The first five are simple types, and the next two (arrays and objects) are compound types. The compound types can package up other arbitrary values of arbitrary type, whereas the simple types cannot.

    In this chapter, let’s discuss in detail about these built-in data types of PHP.

    Integer Data Type in PHP

    A whole number without a decimal point (like 4195) is of int type in PHP. Integer data types are the simplest type. They correspond to simple whole numbers, both positive and negative.

    • An int is a number of the set Z = {…, -2, -1, 0, 1, 2, …}.
    • An int can be represented in a decimal (base 10), hexadecimal (base 16), octal (base 8) or binary (base 2) notation.

    To use octal notation, a number is preceded with “0o” or “0O”. To use hexadecimal notation, precede the number with “0x”. To use binary notation, precede the number with “0b”.

    Given below are some examples −

    • Decimal Integer − 201, 4195, -15
    • Octal Integer − 0o10, 0o12, -0o21
    • Hexadecimal Integer − 0x10, -0x100
    • Binary Integer − 0b10101, -0b100

    Integers can be assigned to variables, or they can be used in expressions, like so −

    $int_var=12345;$another_int=-12345+12345;

    Double Data Type in PHP

    Double variables represent floating point numbers (also known as “floats”, “doubles”, or “real numbers”) that are the numbers with a fractional component. The fractional component follows after the integer component separated by the decimal symbol (.)

    Note − A double variable can be positive, negative, or zero.

    $var1=1.55;$var2=-123.0;

    Scientific Float Notation

    PHP also allows the use of scientific notation to represent a floating point number with more digits after the decimal point. The symbol “E” or “e” is used to separate the integer and fractional part.

    -1.2e3,2.33e-4,7E-10,1.0E5

    By default, doubles print with the minimum number of decimal places needed. Take a look at the following example −

    <?php
       $many = 2.2888800;
       $many_2 = 2.2111200;
       $few = $many + $many_2;
    
       print("$many + $many_2 = $few");
    ?>

    It produces the following output −

    2.28888 + 2.21112 = 4.5
    

    Boolean Data Type in PHP

    The bool type has only two values; it can either be True or False. The bool type is used to express a truth value.

    $bool1=true;$bool2=false;

    You can also use the integer values “1” and “0” to represent True and False Boolean values −

    $bool3=1;$bool4=0;

    Typically, the result of an operator which returns a bool value is passed on to a control structure such as if, while or do-while. For example,

    if(TRUE)print("This will always print.");elseprint("This will never print.");

    Interpreting Other Data Types as Booleans

    Here is a set of rules that you can use to interpret other data types as Booleans −

    • If the value is a number, then it is False only if the value is equal to zero, otherwise the value is True.
    • If the value is a string, it is False if the string is empty (has zero characters) or is the string “0”, and is True otherwise.
    • The values of type NULL are always False.
    • If the value is an array, it is False if it contains no other values; True otherwise. For an object, containing a value means having a member variable that has been assigned a value.
    • Valid resources are true (although some functions that return resources when they are successful will return FALSE when unsuccessful).

    Note − Do not use floating-point numbers (doubles) as Boolean values.

    Each of the following variables has the truth value embedded in its name when it is used in a Boolean context.

    $true_num=3+0.14159;$true_str="Tried and true"$true_array[49]="An array element";$false_array=array();$false_null=NULL;$false_num=999-999;$false_str="";

    String Data Type in PHP

    A string is a sequence of characters, for example, ‘PHP supports string operations.’

    In PHP, a character is the same as a byte. It means PHP only supports a 256 character set, and hence does not offer native Unicode support.

    PHP supports single-quoted as well as double-quoted string formation. Both the following representations are valid in PHP −

    $string_1="This is a string in double quotes";$string_2='This is a somewhat longer, singly quoted string';

    Here are some more examples of string type −

    $string_39="This string has thirty-nine characters";$string_0="";// a string with zero characters

    Single-quoted strings are treated almost literally, whereas double-quoted strings replace variables with their values as well as specially interpreting certain character sequences.

    <?php
       $variable = "name";
       $literally = 'My $variable will not print!';
    
       print($literally);
       print "\n";
    
       $literally = "My $variable will print!";
       print($literally);
    ?>

    When you run this code, it will produce the following output −

    My $variable will not print!
    My name will print
    

    There are no artificial limits on string length. Within the bounds of available memory, you ought to be able to make arbitrarily long strings.

    Strings that are delimited by double quotes (as in “this”) are preprocessed in both the following two ways by PHP −

    • Certain character sequences beginning with backslash (\) are replaced with special characters.
    • Variable names (starting with $) are replaced with string representations of their values.

    The escape-sequence replacements are −

    • \n is replaced by the newline character
    • \r is replaced by the carriage-return character
    • \t is replaced by the tab character
    • \$ is replaced by the dollar sign itself ($)
    • \” is replaced by a single double-quote (“)
    • \\ is replaced by a single backslash (\)

    PHP also has Heredoc and Nowdoc representations of string data type.

    Heredoc Representation of String Data Type

    You can assign multiple lines to a single string variable using heredoc −

    <?php
       $channel =<<<XML
    
       <channel>
    
      &lt;title&gt;What's For Dinner&lt;/title&gt;
      &lt;link&gt;http://menu.example.com/ &lt;/link&gt;
      &lt;description&gt;Choose what to eat tonight.&lt;/description&gt;
    </channel> XML; echo <<< END
      This uses the "here document" syntax to output multiple lines with 
    variable interpolation. Note that the here document terminator must appear on a line with just a semicolon. no extra whitespace! END; print $channel; ?>

    When you run this code, it will produce the following output −

    This uses the "here document" syntax to output
    multiple lines with variable interpolation. Note
    that the here document terminator must appear on a
    line with just a semicolon. no extra whitespace!
    
    <channel>
       <title>What's For Dinner</title>
       <link>http://menu.example.com/ </link>
       <description>Choose what to eat tonight.</description>
    </channel>
    

    Nowdoc Representation of String Data Type

    All the rules for heredoc identifiers also apply to nowdoc identifiers. A nowdoc is specified just like a heredoc, but there is no parsing inside a nowdoc. You can use the nowdoc construct for embedding large blocks of text without having to use any escape characters.

    A nowdoc is identified with the same <<< sequence used for heredocs, but the identifier is enclosed in single quotes, e.g. <<<‘EOT’. Nowdocs apply to single-quoted strings just the way heredocs apply to double-quoted strings.

    Take a look at the following example −

    <?php
       echo <<<'IDENTIFIER'
       As the cat cleared its throat with a refined "Meow",
       the squirrel chirped excitedly about its latest
       discovery of a hidden stash of peanut treasure!
       IDENTIFIER;
    ?>

    Run the code and check its output −

    As the cat cleared its throat with a refined "Meow",
    the squirrel chirped excitedly about its latest
    discovery of a hidden stash of peanut treasure!
    

    Null Data Type in PHP

    In PHP, null represents a special type that only has one value: NULL. Undefined and unset() variables will have the value NULL.

    Programmers normally use the Null data type in PHP to initialize variables or to indicate that a value is missing.

    To give a variable the NULL value, simply assign it like this −

    $my_var=NULL;

    The special constant NULL is capitalized by convention, but actually it is case insensitive; you could just as well have typed −

    $my_var=null;

    A variable that has been assigned NULL has the following properties −

    • It evaluates to FALSE in a Boolean context.
    • It returns FALSE when tested with IsSet() function.

    Note − The data types of variables in PHP are determined at runtime based on the values that are assigned to them.

    Array Data Type in PHP

    An array in PHP is an ordered map, a key is associated with one or more values. A PHP array is defined using the array() function, or with the use of a short notation where the data is put in square brackets.

    Take a look at the following examples of associative arrays −

    Using the array() Function

    $arr=array("foo"=>"bar","bar"=>"foo",);

    Using the Short Notation

    $arr=["foo"=>"bar","bar"=>"foo",];

    An array in PHP can also be defined with the “key-value pair” syntax. It is called an indexed array.

    $arr=array("foo","bar","hello","world");

    In a multi-dimensional array, each element in the main array can also be an array. And, each element in the sub-array can be an array, and so on. Values in the multi-dimensional array are accessed using multiple index.

    Note − In PHP, compound data types are used to store collections of data, including arrays and objects.

    Object Data Type in PHP

    An object type is an instance of a programmer-defined class, which can package up both other kinds of values and functions that are specific to the class.

    To create a new object, use the new statement to instantiate a class −

    classfoo{functionbar(){echo"Hello World.";}}$obj=newfoo;$obj->bar();

    Resource Data Type in PHP

    Resources are special variables that hold references to resources external to PHP (such as a file stream or database connections).

    Here is an example of file resource −

    $fp=fopen("foo.txt","w");

    Data belonging to any of the above types is stored in a variable. However, since PHP is a dynamically typed language, there is no need to specify the type of a variable, as this will be determined at runtime.

    Example: The gettype() Function

    The gettype() function is helpful to find out the type of data stored in a variable −

    <?php
       $x = 10;
       echo gettype($x) . "\n";
    
       $y = 10.55;
       echo gettype($y) . "\n";
    
       $z = [1,2,3,4,5];
       echo gettype($z);
    ?>

    When you run this code, it will produce the following output −

    integer
    double
    array
    

  • Magic Constants

    The magical constants in PHP are predefined constants. They are available to any script on which they run, and they change depending on where they are used. All these “magical” constants are resolved at compile time, unlike regular constants, which are resolved at runtime.

    There are nine magical constants in PHP. These special constants are case insensitive. The list of Magic Constants are as follows −

    • __LINE__
    • __FILE__
    • __DIR__
    • __FUNCTION__
    • __CLASS__
    • __METHOD__
    • __TRAIT__
    • __NAMESPACE__

    __LINE__

    It returns the current line number of the file. The following example shows how you can use this magic constant.

    <?php
       $x="Hello World";
       echo "$x. The current Line number is " . __LINE__ . ".";
    ?>

    Output

    It will produce the following output −

    Hello World. The current Line number is 5.
    

    __FILE__

    This magic constant returns the full path and filename of the file. If used inside an include, the name of the included file is returned. Take a look at the following example −

    <?php
       $x="Hello World";
       echo "$x. Current PHP script name is " . __FILE__ . ".";
    ?>

    Output

    This will produce the following result −

    Hello World. Current PHP script name is C:\xampp\htdocs\hello.php.
    

    __DIR__

    This magical constant returns the directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to “dirname(__FILE__)”. This directory name does not have a trailing slash unless it is the root directory. See the following example −

    <?php
       $x="Hello World";
       echo "$x. Directory of the Current PHP script name is " . __DIR__ . ".";
    ?>

    Output

    It will show the following output on the browser −

    Hello World. Directory of the Current PHP script name is C:\xampp\htdocs.
    

    __FUNCTION__

    This magical constant returns the function name in which the constant is used, or {closure} for anonymous functions. The following example shows how it works −

    <?php
       function hello(){    
    
      $x="Hello World";  
      echo "$x. The function name is ". __FUNCTION__ . "";   
    } hello(); ?>

    Output

    This will generate the below result −

    Hello World. The function name is hello
    

    If this magic constant is used outside the function, then it will give a blank output.

    __CLASS__

    This constant returns the name of a class. The class name includes the namespace it was declared in. See the following example −

    <?php
       class myclass {    
    
      public function __construct() {    
         echo "Inside the constructor of ". __CLASS__ . PHP_EOL;    
      }    
      function getClassName(){                      
         echo "from an instance method of " . __CLASS__ . "";   
      }    
    } $obj = new myclass; $obj->getClassName(); ?>

    Output

    This will create the below outcome −

    Inside the constructor of myclass
    from an instance method of myclass
    

    __METHOD__

    The __METHOD__ constant returns the class method name. The following example shows how it works −

    <?php
       class myclass {    
    
      public function __construct() {    
         echo "Calling " . __METHOD__ . " of " . __CLASS__ ."&lt;br&gt;";
      }    
      function mymethod(){                      
         echo "Calling " . __METHOD__ . " of " . __CLASS__ ."";
      }    
    } $obj = new myclass; $obj->mymethod(); ?>

    Output

    This will lead to the following outcome −

    Calling myclass::__construct of myclass
    Calling myclass::mymethod of myclass
    

    __TRAIT__

    It returns the trait name. The trait name includes the namespace it was declared in. In PHP, traits are a mechanism for code reuse. A trait is similar to a class, but only intended to group functionality in a fine-grained and consistent way. It is not possible to instantiate a trait on its own.

    Take a look at the following example −

    <?php
       trait mytrait {
    
      public function hello() {
         echo "Hello World from " . __TRAIT__ ."";
      }
    } class myclass {
      use mytrait;
    } $obj = new myclass(); $obj->hello(); ?>

    Output

    The result of this PHP code is −

    Hello World from mytrait
    

    __NAMESPACE__

    This constant returns the name of the current namespace. In PHP, namespaces allow us to use classes / functions / constants of same name in different contexts without any conflict, thereby encapsulating these items. A namespace is a logical grouping of classes/functions depending on their relevance.

    The following example shows how you can use this magic constant −

    <?php
       namespace myspace;
       class myclass {    
    
      public function __construct() {    
         echo "Name of the class: " . __CLASS__ . " in " . __NAMESPACE__ . ""; 
      }     
    } $class_name = __NAMESPACE__ . '\myclass'; $a = new $class_name; ?>

    Output

    It will generate the following outcome −

    Name of the class: myspace\myclass in myspace
    

    ClassName::class

    Unlike the other magic constants, this magic constant does not start and end with the double underscore (__). It returns the fully qualified class name.

    The following example shows how you can use this magic constant −

    <?php
       namespace myspace;
       class myclass {    
    
      public function __construct() {    
         echo "Name of the class: " . myclass::class ;
      }     
    } use myspace; $a = new myclass; ?>

    Output

    The following will be the outcome of this code −

    Name of the class: myspace\myclass
  • Constants

    A constant in PHP is a name or an identifier for a simple value. A constant value cannot change during the execution of the PHP script. It basically improves code readability and maintainability. Constants make it easier to manage the configuration settings.

    They make code easier to read and prevent key values from changing. Constants can be used anywhere in the application. PHP also contains built-in constants such as PHP_VERSION. Constants help make the code simple and secure.

    Rules of Constants in PHP

    • By default, a PHP constant is case-sensitive.
    • By convention, constant identifiers are always uppercase.
    • A constant name starts with a letter or underscore, followed by any number of letters, numbers, or underscore.
    • There is no need to write a dollar sign ($) before a constant, however one has to use a dollar sign before a variable.

    How to Define a Constant in PHP?

    We can use the define() function to create a constant in PHP programming language.

    Syntax

    Below is the syntax of the define() function in PHP −

    define("CONSTANT_NAME", value);

    Parameters

    The parameters are needed to use the define() function are mentioned below −

    Sr.NoParameter & Description
    1CONSTANT_NAMEIt is the name of the constant (should be in uppercase).
    2valueIt is the fixed value assigned to the constant.

    Rules for Defining Constants

    Here are the rules listed below for defining a constant −

    • A constant name must start with a letter or underscore.
    • Unlike variables, a constant name should not contain the $ sign.
    • Constants are global, so they can be accessed from anywhere in the script.

    Examples of Valid and Invalid Constant Names in PHP

    Here are some examples of valid and invalid constant names in PHP −

    // Valid constant namesdefine("ONE","first thing");define("TWO2","second thing");define("THREE_3","third thing");define("__THREE__","third value");// Invalid constant namesdefine("2TWO","second thing");

    PHP Predefined Constants

    PHP has several built-in constants which provide useful information.

    <?php
       // Provides the current PHP version
       echo PHP_VERSION; 
       
       // Provides the operating system PHP is running on
       echo PHP_OS; 
    ?>

    Defining a Named Constant

    The define() function in PHP library is used to define a named constant at runtime.

    define(string$const_name,mixed$value,bool$case=false):bool

    Parameters

    • const_name − The name of the constant.
    • value − The value of the constant. It can be a scalar value (int, float, string, bool, or null) or array values are also accepted.
    • case − If set to true, the constant will be defined case-insensitive. The default behavior is case-sensitive, i.e., CONSTANT and Constant represent different values.

    The define() function returns “true” on success and “false” on failure.

    Example 1

    The following example demonstrates how the define() function works −

    <?php  
       define("CONSTANT", "Hello world.");
    
       echo CONSTANT; 
       // echo Constant; 
    ?>

    Output

    The first echo statement outputs the value of CONSTANT. You will get the following output −

    Hello world.
    

    But, when you uncomment the second echo statement, it will display the following error −

    Fatal error: Uncaught Error: Undefined constant "Constant" in hello.php: on line 5
    

    If you set the case parameter to False, PHP doesn’t differentiate upper and lowercase constants.

    Example 2

    You can also use an array as the value of a constant. Take a look at the following example −

    <?php  
       define(
    
      $name="LANGS", 
      $value=array('PHP', 'Java', 'Python')
    ); var_dump(LANGS); ?>

    Output

    It will produce the following output −

    array(3) {
      [0]=>
      string(3) "PHP"
      [1]=>
      string(4) "Java"
      [2]=>
      string(6) "Python"
    }
    

    Using the constant() Function

    The echo statement outputs the value of the defined constant. You can also use the constant() function. It returns the value of the constant indicated by name.

    constant(string$name):mixed

    The constant() function is useful if you need to retrieve the value of a constant, but do not know its name. I.e. it is stored in a variable or returned by a function.

    <?php
       define("MINSIZE", 50);
    
       echo MINSIZE;
       echo PHP_EOL;
       // same thing as the previous line
       echo constant("MINSIZE");	
    ?>

    Output

    It will produce the following output −

    50
    50
    

    Using the defined() Function

    The PHP library provides a defined() function that checks whether a given named constant exists. Take a look at the following example −

    <?php
       define('MAX', 100);
    
       if (defined('MAX')) {
    
      echo MAX;
    } ?>

    Output

    It will produce the following output −

    100
    

    PHP also has a function called “get_defined_constants()” that returns an associative array of all the defined constants and their values.

    Difference between Constants and Variables in PHP

    • Constants cannot be defined by simple assignment; they can only be defined using the define() function.
    • Constants may be defined and accessed anywhere without regard to variable scoping rules.
    • Once the Constants have been set, they may not be redefined or undefined.
  • $ and $$ Variables

    PHP is a powerful scripting language created specifically for web development. One of its unique features is the use of variables. Variables in PHP begin with the dollar symbol ($). But there is another type of variable known as a $$ (double dollar sign) variable, which is a variable within itself.

    In this chapter, we are going to learn about these variables through simple examples.

    What is a $ Variable?

    A $ variable is a normal PHP variable that contains a value. A variable can be allocated a wide range of values, including numbers, texts and arrays.

    Example

    Here is the basic usage of $ variable in which we have declared a variable $name and assign it the value. And with the help of echo, we print the value stored in $name −

    <?php   
       $name = "Akshita";
       echo $name; 
       // Output: Akshita
    ?>

    Normal vs Dynamic Variables

    Normal Variable: The declaration of a normal variable is like this −

    <?php  
       $a = 'good';
    ?>

    Dynamic Variable: A dynamic variable takes the value of a normal variable and treats that as the name of the variable. In the above example, “good” can be used as the name of a variable by using two dollar signs “$$” −

    <?php     
       $$a = 'morning';
    ?>

    We now have two variables: “$a” with contents “good” and “$$a” with contents “morning”. As a result, the following echo statements will produce the same output −

    <?php  
       $a = 'good';
       $$a = 'morning';
    
       echo "$a {$$a}\n";
       echo "$a $good";
    ?>

    Output

    Both produce the same output −

    good morning
    good morning
    

    Example – Using Dynamic Variables

    Take a look at this following example −

    <?php  
       $a = 'good';
       $$a = 'morning';
    
       echo "$a {$$a}\n";
       echo "$a $good";
    ?>

    Output

    It will produce the following output −

    good morning
    good morning
    

    Example

    Let’s take a look at another example −

    <?php  
       $x = "foo";  
       $$x = "bar";  
       echo "Value of x = " .$x . "\n";  
       echo 'Value of $$x = ' . $$x . "\n";  
       echo 'Value of foo = ' . $foo;  
    ?>

    Output

    Here, you will get the below outcome −

    Value of x = foo
    Value of $$x = bar
    Value of foo = bar
    

    What is a $$ Variable?

    A $$ variable is a variable within a variable. It means that the variable’s name is saved in another variable.

    Note that the use of “$” symbol is not restricted to two. Any number of dollar symbols can be prefixed.

    Suppose there is a variable “$x” with “a” as its value. Next, we define $$x=’as’, then “$$x” as well as “$a” will have the same value. Similarly, the statement $$$x=’and’ effectively declares a “$as” variable whose value is ‘and’.

    Example with Multiple $ Symbols

    Here is a complete example that shows the use of multiple “$” symbols.

    <?php  
       $php = "a";
       $lang = "php";
       $World = "lang";
       $Hello = "World";
       $a = "Hello";
       echo '$a= ' . $a;
       echo "\n";
       echo '$$a= ' . $$a;
       echo "\n";
       echo '$$$a= ' . $$$a;
       echo "\n";
       echo '$$$$a= ' . $$$$a;
       echo "\n";
       echo '$$$$$a= ' . $$$$$a;
    ?>

    Output

    When you run this code, it will produce the following result −

    $a= Hello
    $$a= World
    $$$a= lang
    $$$$a= php
    $$$$$a= a
    

    Using Dynamic Variables with Arrays

    Using dynamic variables with arrays may lead to certain ambiguous situations. With an array “a”, if you write $$a[1], then the parser needs to know if you are refering to “$a[1]” as a variable or if you want “$$a” as the variable and then the [1] index from that variable.

    To resolve this ambiguity, use ${$a[1]} for the first case and ${$a}[1] for the second.

    Example

    Take a look at the following example −

    <?php  
       $vars = array("hw", "os", "lang");
       $var_hw="Intel";
       $var_lang="PHP";
       $var_os="Linux";
    
       foreach ($vars as $var)
    
      echo ${"var_$var"} . "\n";
    print "$var_hw\n$var_os\n$var_lang"; ?>

    Output

    It will produce the following output −

    Intel
    Linux
    PHP
    Intel
    Linux
    PHP
    

    It may be noted that this technique cannot be used with PHP’s Super-global arrays (Several predefined variables in PHP are “superglobals”, which means they are available in all scopes throughout a script) within functions or class methods. The variable “$this” is a special variable in PHP and it cannot be referenced dynamically.

  • var dump Function

    The PHP Variable Handling var_dump() function is used to display structured information such as type and the value of one or more expressions given as arguments to this function.

    This function returns all the public, private and protected properties of the objects in the output. The dump information about arrays and objects is properly indented to show the recursive structure.

    For the built-in integer, float and Boolean variables, the var_dump() function shows the type and value of the argument variable.

    If an object has a special __debugInfo() function, var_dump() follows it. You can also use var_dump() on many variables simultaneously. This function prints the output immediately, but it can also be saved using the output-control functions.

    Syntax

    Below is the syntax of the PHP Variable Handling var_dump() function −

    voidvar_dump(mixed$value,mixed...$values)

    Parameters

    Below are the parameters of the var_dump() function −

    • $value − It is the variable you want to check.
    • $values − It is the more variables that you want to check. It is an optional parameter.

    Return Value

    The var_dump() function does not return anything. It just prints information on the screen.

    PHP Version

    First introduced in core PHP 4, the var_dump() function continues to function easily in PHP 5, PHP 7, and PHP 8.

    Example 1

    First we will show you the basic example of the PHP Variable Handling var_dump() function to display detailed information about the given variable.

    <?php
       $x = 10;  
       var_dump ($x);
    ?>

    Output

    The dump information is as follows −

    int(10)
    

    Example 2

    Now we will see how the var_dump() function behaves for a float variable. See the below code −

    <?php
       $x = 10.25;  
       var_dump ($x);
    ?>

    Output

    The var_dump() function returns the following output −

    float(10.25)
    

    Example 3

    In the below PHP code we will use the var_dump() function. Here we can use the </pre> HTML tag that displays preformatted text. Text in a </pre> element is displayed in a fixed-width font, and the text preserves both the spaces and the line breaks.

    <?php
       echo "</pre>";
       $x = "Hello World"; 
       var_dump ($x);  
       echo "</pre>"
    ?>

    Output

    The above code will generate the below output −

    string(11) "Hello World"
    

    Example 4

    The var_dump() function is useful to study the array structure. In the following example, we have an array with one of the elements of the array being another array. In other words, we have a nested array situation.

    <?php
       $x = array("Hello", false, 99.99, array(10, 20,30));
       var_dump ($x);
    ?>

    Output

    This will create the below output −

       array(4) {
       [0]=>
       string(5) "Hello"
       [1]=>
       bool(false)
       [2]=>
       float(99.99)
       [3]=>
       array(3) {
    
      [0]=&gt;
      int(10)
      [1]=&gt;
      int(20)
      [2]=&gt;
      int(30)
    } }

    Example 5

    Since “$x” is an indexed array in the previous example, the index starting with “0” along with its value is dumped. In case the array is an associate array, the key-value pair information is dumped.

    <?php
       $x = array(
    
      "Hello", false, 99.99, 
      array(1=&gt;10, 2=&gt;20,3=&gt;30)
    ); var_dump($x); ?>

    Output

    Following is the output of the above code −

    array(4) {
      [0]=>
      string(5) "Hello"
      [1]=>
      bool(false)
      [2]=>
      float(99.99)
      [3]=>
      array(3) {
    
    [1]=&gt;
    int(10)
    [2]=&gt;
    int(20)
    [3]=&gt;
    int(30)
    } }

    When you use var_dump() to show array value, there is no need of using the end tag ” </pre> “.

    Example 6

    The var_dump() function can als reveal the properties of an object representing a class. In the following example, we have declared a Point class with two private properties “x” and “y”. The class constructor initializes the object “p” with the parameters passed to it.

    The var_dump() function provides the information about the object properties and their corresponding values.

    <?php  
       class Point {
    
      private int $x;
      private int $y;
      public function __construct(int $x, int $y = 0) {
         $this-&gt;x = $x;
         $this-&gt;y = $y;
      }
    } $p = new Point(4, 5); var_dump($p) ?>

    Output

    It will produce the following output −

    object(Point)#1 (2) {
      ["x":"Point":private]=>
      int(4)
      ["y":"Point":private]=>
      int(5)
    }
    

    There is a similar built-in function for producing dump in PHP, named as get_defined_vars().

    var_dump(get_defined_vars());

    It will dump all the defined variables to the browser.