Author: Saim Khalid

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

    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 PHP’s 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. 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 − 0010, 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 only 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 − Don’t use double as Booleans.

    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 resolve to 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.

    __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__ . ".";
    ?>

    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__ . ".";
    ?>

    It will produce the following output −

    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__ . ".";
    ?>

    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(); ?>

    It will produce the following output −

    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(); ?>

    It will produce the following output −

    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(); ?>

    It will produce the following output −

    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(); ?>

    It will produce the following output −

    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; ?>

    It will produce the following output −

    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; ?>

    It will produce the following output −

    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.

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

    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");

    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.

    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; 
    ?>

    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); ?>

    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;
       echo constant("MINSIZE");	// same thing as the previous line
    ?>

    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;
    } ?>

    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.

  • $ and $$ Variables

    We know that PHP uses the convention of prefixing the variable names by the “$” symbol. PHP also has the provision of declaring dynamic variables by prefixing two dollar symbols ($$) to the name. A variable variable (or a dynamic variable) can be set and used dynamically.

    The declaration of a normal variable is like this −

    $a='good';

    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 “$$” −

    $$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 −

    echo"$a {$$a}";echo"$a $good";

    Both produce the same output −

    good morning
    

    Example 1

    Take a look at this following example −

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

    It will produce the following output −

    good morning
    good morning
    

    Example 2

    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;  
    ?>

    Here, you will get the following output −

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

    Using Multiple “$” Symbols

    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

    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;
    ?>

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

    $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"; ?>

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

  • PHP var_dump() Function

    ne of the built-in functions in PHP is the var_dump() function. This function displays structured information such as type and the value of one or more expressions given as arguments to this function.

    var_dump(mixed$value,mixed...$values):void

    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 varibles, the var_dump() function shows the type and value of the argument variable.

    Example 1

    For example, here is an integer variable −

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

    The dump information is as follows −

    int(10)
    

    Example 2

    Let’s see how it behaves for a float variable −

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

    The var_dump() function returns the following output −

    float(10.25)
    

    Example 3

    If the expression is a Boolean value −

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

    It will produce the following output −

    bool(true)
    

    Example 4

    For a string variable, the var_dump() function returns the length of the string also.

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

    It will produce the following output −

    string(11) "Hello World"
    

    Here we can use the <pre> HTML tag that dislays 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>"
    ?>

    It will produce the following output −

    string(11) "Hello World"
    

    Example 5 – Studying the Array Structure Using var_dump()

    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);
    ?>

    It will produce the following output −

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

    Example 6

    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); ?>

    Here, you will get the following output −

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

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

    Example 7

    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 corrcponding 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) ?>

    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/Print

    In PHP, both echo and print statements are used to render the output either on the browser or the PHP console. Both of them are not functions but they are language constructs. Hence, parentheses should not be used with either of them.

    The “echo” Statement in PHP

    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.

    Example

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

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

    It will produce the following output −

    Hello Rajesh How are you?
    

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

    echo'Hello '.$name.' How are you?';

    Example

    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 = "Rajesh";
       echo "Hello $name How are you?";
    ?>

    It will produce the following output −

    Hello Rajesh How are you?
    

    Example

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

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

    It will produce the following output −

    Hello $name How are you?
    

    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 −

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

    Example

    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";
    ?>

    It will produce the following output −

    helloworld
    

    The “print” Statement in PHP

    The print statement is similar to echo, but it outputs an expression.

    print(string$expression):int

    Like echo, print is also a language construct. Its argument is an expression but it is not put in parentheses.

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

    Example

    Take a look at this following example −

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

    It will produce the following output −

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

    Output Multiline Strings Using Print/Echo

    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
       ";  
    ?>

    It will produce the following output −

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

    A variable in PHP is a named memory location that holds data belonging to one of the data types.

    • PHP uses the convention of prefixing a dollar sign ($) to the name of a variable.
    • Variable names in PHP are case-sensitive.
    • Variable names follow the same rules as other labels in PHP. A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores.
    • As per the naming convention, “$name”, “$rate_of_int”, “$Age”, “$mark1” are examples of valid variable names in PHP.
    • Invalid variable names: “name” (not having $ prefix), “$rate of int” (whitespace not allowed), “$Age#1” (invalid character #), “$11” (name not starting with alphabet).

    Variables are assigned with the “=” operator, with the variable on the left hand side and the expression to be evaluated on the right.

    No Need to Specify the Type of a Variable

    PHP is a dynamically typed language. There is no need to specify the type of a variable. On the contrary, the type of a variable is decided by the value assigned to it. The value of a variable is the value of its most recent assignment.

    Take a look at this following example −

    <?php
       $x = 10;
       echo "Data type of x: " . gettype($x) . "\n";
    
       $x = 10.55;
       echo "Data type of x now: " . gettype($x) . "";
    ?>

    It will produce the following output −

    Data type of x: integer
    Data type of x now: double
    

    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;
    ?>

    It will produce the following output −

    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 doesn’t 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 . "";
    ?>

    It will produce the following output −

    (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 . "";
    ?>

    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

    Variable Naming

    Rules for naming a variable is −

    • Variable names must begin with a letter or underscore character.
    • A variable name can consist of numbers, letters, underscores but you cannot use characters like + , – , % , ( , ) . & , etc

    There is no size limit for variables.

  • Comments

    A comment in any computer program (such as a PHP program) is a certain explanatory text that is ignored by the language compiler/interpreter. Its purpose is to help the user understand the logic used in the program algorithm.

    Although placing comments in the code is not essential, it is a highly recommended practice. The comments also serve as program documentation. Comments are also useful when the code needs to be debugged and modified.

    There are two commenting formats in PHP −

    • Single-line Comments
    • Multi-line Comments

    Single-line Comments

    They are generally used for short explanations or notes relevant to the local code. PHP uses two notations for inserting a single-line comment in a program.

    Single-line Comments Using “#”

    A line in PHP code starting with the “#” symbol is treated as a single-line comment.

    <?php
       # Single line comment starting with # symbol
       echo 'Hello World';
    ?>

    Single-line Comments Using “//”

    PHP also supports C style of single-line comments with “//” symbol. A line starting with double oblique symbol is treated as a comment.

    <?php
       // Single line comment starting with // symbol
       echo 'Hello World';
    ?>

    A comment that starts with the symbol “#” or “//” need not be closed. The effect of these symbols last till the end of the physical line.

    In other words, the PHP parser will treat the next line as a PHP statement and not as a comment even if there is no closing comment marker.

    Multi-line Comments

    Multi-line comments are generally used to provide pseudocode algorithms and more detailed explanations when necessary.

    The multiline style of commenting is the same as in C. One or more lines embedded inside the “/*” and “*/” symbols are treated as a comment.

    Example of Multi-line Comment in PHP

    Here is the example of a multi-line comment.

    <?php
    
       /* This is a multiline comment example
       program to add two numbers
       Variables used - $x for first number, 
       $y for second number */
       
       $x=10;
       $y=20;
       print "Total = ". $x+$y;
    ?>

    Note that you can put even a single line inside the “/* .. */” symbols. However, if there is a “/*” symbol in the program, it must have a closing end-of comment marker “*/”. If not, an error will be displayed as follows −

    PHP Parse error:  Unterminated comment starting line 3 in /home/cg/root/65ded9eeb52fc/main.php on line 3
  • Hello World

    Conventionally, learners write a “Hello World” program as their first program when learning a new language or a framework. The objective is to verify if the software to be used has been installed correctly and is working as expected. To run a Hello World program in PHP, you should have installed the Apache server along with PHP module on the operating system you are using.

    PHP is a server-side programming language. The PHP code must be available in the document root of the web server. The web server document root is the root directory of the web server running on your system. The documents under this root are accessible to any system connected to the web server (provided the user has permissions). If a file is not under this root directory, then it cannot be accessed through the web server.

    In this tutorial, we are using XAMPP server software for writing PHP code. The default document root directory is typically “C:\xampp\htdocs\” on Windows and “/opt/lamp/htdocs/” on Linux. However, you can change the default document root by modifying the DocumentRoot setting in Apache server’s configuration file “httpd.conf”.

    While on a Windows operating system, start the Apache server from the XAMPP control panel.

    PHP Hello World

    Browse to the “htdocs” directory. Save the following script as “hello.php” in it.

    <?php
       echo "Hello World!";
    ?>

    Open a new tab in your browser and enter http://localhost/hello.php as the URL. You should see the “Hello World” message in the browser window.

    A PHP script may contain a mix of HTML and PHP code.

    <!DOCTYPE html><html><body><h1>My PHP Website</h1><?php
    
      echo "Hello World!";
    ?></body></html>

    The “Hello World” message will be rendered as a plain text. However, you can put HTML tags inside the “Hello World” string. The browser will interpret the tags accordingly.

    In the following code, the “echo” statement renders “Hello World” so that it is in <h1> heading with the text aligned at the center of the page.

    <?php
       echo "<h1 align='center'>Hello World!</h1>";
    ?>

    PHP Script from Command Prompt

    You can run your PHP script from the command prompt. Let’s assume you have the following content in your “hello.php” file.

    <?php
       echo "Hello PHP!!!!!";
    ?>

    Add the path of the PHP executable to your operating system’s path environment variable. For example, in a typical XAMPP installation on Windows, the PHP executable “php.exe” is present in “c:\xampp\php” directory. Add this directory in the PATH environment variable string.

    Now run this script as command prompt −

    C:\xampp\htdocs>php hello.php
    

    You will get the following output −

    Hello PHP!!!!!