Category: Basic

  • 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.

  • Echo and Print

    PHP uses the echo and print statements to display output in the browser or the PHP console. Both are language structures rather than functions, indicating that they are part of the PHP language. As a result, using parentheses is optional. These instructions are commonly used to display text, numbers, variables and even HTML content directly on a website. While they serve the same purpose there are some small differences between them. Echo can accept several parameters and is faster than print, which returns a result of 1, making it suitable to use in expressions.

    What is Echo?

    Echo is a PHP statement that displays data. It does not return a value but can produce multiple values at once.

    Syntax

    The echo statement is used with following syntax −

    echo(string...$expressions):void

    The echo statement outputs one or more expressions, with no additional newlines or spaces.

    Basic Usage of echo in PHP

    Here is an example of how the echo statement works in PHP −

    <?php
       $name = "Rahul";
       echo "Hello " . $name . " How are you?"
    ?>

    Output

    It will produce the below outcome −

    Hello Rahul How are you?
    

    Using Single-Quoted String in echo

    Since a double quoted string is similar to a single quoted string in PHP, the following statement produces the same output.

    <?php
       echo 'Hello ' . $name . ' How are you?';
    ?>

    Using Double-Quoted String in echo

    A double quoted string outputs the value of the variable. Hence, the following statement inserts the value of “$name” variable before printing the output.

    <?php
       $name = "Rahul";
       echo "Hello $name How are you?";
    ?>

    Output

    It will produce the following result −

    Hello Rahul How are you?
    

    Single-Quoted String Treats Variables as Plain Text

    But, a single-quoted string will output “$name” as it is.

    <?php
       $name = "Rahul";
       echo 'Hello $name How are you?';
    ?>

    Output

    It will produce the following output −

    Hello $name How are you?
    

    Passing Multiple Arguments in echo

    A string passed to an echo statement can either be passed individually as multiple arguments or concatenated together and passed as a single argument. So, both the following statements are valid −

    <?php
       echo 'Hello ', 'how ', 'are ', 'you?', "\n";
       echo 'Hello ' . 'how ' . 'are ' . 'you?' . "\n";
    ?>

    Output

    Here is the output of the above example −

    Hello how are you?
    Hello how are you?
    

    Successive echo Statements Without a Newline

    Note that output of the two successive echo statements will be rendered in the same line if the newline character is not used. Take a look at the following example −

    <?php
       echo "hello";
       echo "world";
    ?>

    Output

    It will generate the below result −

    helloworld
    

    What is Print?

    The PHP print statement is the same as the echo statement and can be used to replace it several times. It is also a language construct, thus we can not use parenthesis, like print or print().

    The major difference is that the print statement in PHP accepts a single argument only and always returns 1.

    Syntax

    The print statement is similar to echo, but it outputs an expression. Check the syntax below −

    print(string$expression):int

    Basic Usage of print in PHP

    Take a look at the basic usage of the print in PHP −

    <?php
       $name = "Rajesh";
    
       print "Hello " . $name . " How are you?\n";
       print "Hello $name How are you?";
    ?>

    Output

    Following is the output of the above code −

    Hello Rajesh How are you?
    Hello Rajesh How are you?
    

    Output Multiline Strings Using Print

    Both echo and print statements can output multiline strings spanning over more than one lines in the editor. Take a look at the following example −

    <?php
       print "
       Multi-line
       string can be output  
       by echo as well as 
       print statement in PHP
       ";  
    ?>

    Output

    This will create the below output −

    Multi-line
    string can be output
    by echo as well as
    print statement in PHP
    

    The output will remain the same if we replace print with echo.

    Echo vs Print: Key Differences

    Below are the key differences of echo and print in a tabular form −

    FeatureEchoPrint
    SpeedFasterSlower
    Return ValueNoYes (1)
    Multiple ArgumentsYesNo

    When to Use Echo or Print?

    In most cases, use “echo” over “print” in PHP as it is considered to be faster, can output multiple strings at once separated by commas and does not return a value, making it more efficient for simple text display; whereas “print” is better suited for situations where a return value is required within an expression because of its “1” return value and can only output a single string at a time.

    Conclusion

    Both echo and print are effective methods for presenting data in PHP. Echo is frequently preferred for faster performance, but print is useful when a return value is necessary.

    Learning their differences helps you to use them more effectively in PHP projects.

  • Variables

    Variables in PHP are used to store data that can be accessed and modified across the program. A variable can store a wide range of values, like numbers, text, arrays and even objects. One of PHP’s unique features is that it is a loosely typed language, which means you are not required to declare the data type of a variable when you create it. PHP defines the variable’s type based on the value assigned to it.

    This freedom makes PHP easier to use, particularly for beginners, because it allows you to store and manage a variety of data types without having to design them yourself.

    Table of Content

    • How to Declare a Variable in PHP?
    • PHP Variable Rules
    • Variable Types in PHP
    • Automatic Type Conversion of Variables
    • Variables are Assigned by Value
    • Assigning Values to PHP Variables by Reference
    • Variable Scope

    How to Declare a Variable in PHP?

    To declare a variable in PHP, just assign a value by typing the $ symbol followed by the variable name. PHP variables are case-sensitive and should begin with a letter or an underscore, followed by any number of letters, numbers or underscores.

    Syntax

    $variable_name= value;

    Example

    Here is an example showing how to declare variables in PHP −

    // A string value$name="John";// A number (integer)$age=25;// A decimal number (float)$price=12.50;

    PHP Variable Rules

    Here is the list of rules to define a variable in PHP −

    • A variable must start with a $ symbol, then its name.
    • The variable name must start with a letter or underscore (_).
    • A variable name cannot start with a number.
    • The variable name can contain letters, digits or underscores.
    • PHP is case sensitive, so $Name and $name are distinct variables.

    Example

    See the below example showing how both the variables $Name and $name are different to each other and see the output of the code.

    $Name="Amit";$name="Samay";echo$Name;echo$name;

    Output

    Following is the result of the above code −

    Amit
    Samay
    

    Variable Types in PHP

    In PHP, the primary variable types are string, integer, float (also known as double), Boolean, array, object, null, and resource. Below is the example of each type of variable.

    • String : A sequence of characters.
    • Integer : A whole number (without decimals).
    • Float (Double) : A decimal number.
    • Boolean : Represents true or false values.
    • Array : Stores multiple values in one variable.
    • NULL : Represents a variable with no value.

    Automatic Type Conversion of Variables

    PHP does a good job of automatically converting types from one to another when necessary. In the following code, PHP converts a string variable “y” to “int” to perform addition with another integer variable and print 30 as the result.

    Take a look at this following example −

    <?php
       $x = 10;
       $y = "20";
    
       echo "x + y is: ", $x+$y;
    ?>

    Output

    It will generate the following outcome −

    x + y is: 30
    

    Variables are Assigned by Value

    In PHP, variables are always assigned by value. If an expression is assigned to a variable, the value of the original expression is copied into it. If the value of any of the variables in the expression changes after the assignment, it doesnt have any effect on the assigned value.

    <?php
       $x = 10;
       $y = 20;
       $z = $x+$y;
       echo "(before) z = ". $z . "\n";
    
       $y=5;
       echo "(after) z = ". $z . "";
    ?>

    Output

    It will produce the below result −

    (before) z = 30
    (after) z = 30
    

    Assigning Values to PHP Variables by Reference

    You can also use the way to assign values to PHP variables by reference. In this case, the new variable simply references or becomes an alias for or points to the original variable. Changes to the new variable affect the original and vice versa.

    To assign by reference, simply prepend an ampersand (&) to the beginning of the variable which is being assigned (the source variable).

    Take a look at this following example −

    <?php
       $x = 10;
       $y = &$x;
       $z = $x+$y;
       echo "x=". $x . " y=" . $y . " z = ". $z . "\n";
    
       $y=20;
       $z = $x+$y;
       echo "x=". $x . " y=" . $y . " z = ". $z . "";
    ?>

    Output

    It will produce the following output −

    x=10 y=10 z = 20
    x=20 y=20 z = 40
    

    Variable Scope

    Scope can be defined as the range of availability a variable has to the program in which it is declared. PHP variables can be one of four scope types −

    • Local Variables
    • Global Variables
    • Static Variables
    • Function Parameters