PHP – Global Variables

PHP – Global Variables ”; Previous Next In PHP, any variable that can be accessed from anywhere in a PHP script is called as a global variable. If the variable is declared outside all the functions or classes in the script, it becomes a global variable. While global variables can be accessed directly outside a function, they aren’t automatically available inside a function. Example In the script below, $name is global for the function sayhello(). <?php $name = “Amar”; function sayhello() { echo “Hello ” . $name; } sayhello(); ?> However, the variable is not accessible inside the function. Hence, you will get an error message “Undefined variable $name”. Hello PHP Warning: Undefined variable $name in /home/cg/root/93427/main.php on line 5 Example To get access within a function, you need to use the “global” keyword before the variable. <?php $name = “Amar”; function sayhello() { GLOBAL $name; echo “Hello ” . $name; } sayhello(); ?> It will produce the following output − Hello Amar If a function accesses a global variable and modifies it, the modified value is available everywhere after the function call is completed. Let us change the value of $name inside the sayhello() function and check its value after the function is called. Example Take a look at this following example − <?php $name = “Amar”; function sayhello() { GLOBAL $name; echo “Global variable name: $name” .PHP_EOL; $name = “Amarjyot”; echo “Global variable name changed to: $name” .PHP_EOL; } sayhello(); echo “Global variable name after function call: $name” .PHP_EOL; ?> It will produce the following output − Global variable name: Amar Global variable name changed to: Amarjyot Global variable name after function call: Amarjyot The $GLOBALS Array PHP maintains an associative array named $GLOBALS that holds all the variables and their values declared in a global scope. The $GLOBALS array also stores many predefined variables called as superglobals, along with the user defined global variables. Any of the global variables can also be accessed inside any function with the help of a regular syntax of accessing an arrow element. For example, the value of the global variable $name is given by $GLOBALS[“name”]. Example In the following example, two global variable $x and $y are accessed inside the addition() function. <?php $x = 10; $y = 20; function addition() { $z = $GLOBALS[”x”]+$GLOBALS[”y”]; echo “Addition: $z” .PHP_EOL; } addition(); ?> It will produce the following output − Addition: 30 Example You can also add any local variable into the global scope by adding it in the $GLOBALS array. Let us add $z in the global scope. <?php $x = 10; $y = 20; function addition() { $z = $GLOBALS[”x”]+$GLOBALS[”y”]; $GLOBALS[”z”] = $z; } addition(); echo “Now z is the global variable. Addition: $z” .PHP_EOL; ?> It will produce the following output − Now z is the global variable. Addition: 30 Including One PHP Script in Another You can include one PHP script in another. Variables declared in the included script are added in the global scope of the PHP script in which it is included. Here is “a.php” file − <?php include ”b.php”; function addition() { $z = $GLOBALS[”x”]+$GLOBALS[”y”]; echo “Addition: $z” .PHP_EOL; } addition(); ?> It includes “b.php” that has the $x and $y variables, so they become the global variables for the addition() function in “a.php” script. <?php $x = 10; $y = 20; ?> Global variables are generally used while implementing singleton patterns, and accessing registers in embedded systems and also when a variable is being used by many functions. Print Page Previous Next Advertisements ”;

PHP – $_REQUEST

PHP – $_REQUEST ”; Previous Next In PHP, $_REQUEST is a superglobal variable. It is an associative array which is a collection of contents of $_GET, $_POST and $_COOKIE variables. The settings in your “php.ini” file decides the composition of this variable. One of the directives in “php.ini” is request_order, which decides the order in which PHP registers GET, POST and COOKIE variables. The presence and order of variables listed in this array is defined according to the PHP variables_order. If a PHP script is run from the command line, the argc and argv variables are not included in the $_REQUST array because their values are taken from the $_SERVER array, which in turn is populated by the web server. $_REQUEST with GET Method Save the following script in the document folder of the Apache server. If you are using XAMPP server on Windows, place the script as “hello.php” in the “c:/xampp/htdocs” folder. <html> <body> <?php echo “<h3>First Name: ” . $_REQUEST[”first_name”] . “<br />” . “Last Name: ” . $_REQUEST[”last_name”] . “</h3>”; ?> </body> </html> Start the XAMPP server and enter http://localhost/hello.php?first_name=Amar&last_name=Sharma as the URL in a browser window. You should get the output as − $_REQUEST with POST Method Under the document root, save the following script as “hello.html”. <html> <body> <form action=”hello.php” method=”post”> First Name: <input type=”text” name=”first_name” /> <br /> Last Name: <input type=”text” name=”last_name” /> <input type=”submit” value=”Submit” /> </form> </body> </html> In your browser, enter the URL “http://localhost/hello.html”. You should get the similar output in the browser window. You may also embed the PHP code inside the HTML script and POST the form to itself with the PHP_SELF variable − <html> <body> <form action=”<?php echo $_SERVER[”PHP_SELF”];?>” method=”post”> <p>First Name: <input type=”text” name=”first_name” /></p> <p>Last Name: <input type=”text” name=”last_name” /></p> <input type=”submit” value=”Submit” /> </form> <?php if ($_SERVER[“REQUEST_METHOD”] == “POST”) echo “<h3>First Name: ” . $_REQUEST[”first_name”] . “<br />” . “Last Name: ” . $_REQUEST[”last_name”] . “</h3>”; ?> </body> </html> It will produce the following output − Print Page Previous Next Advertisements ”;

PHP – Local Variables

PHP – Local Variables ”; Previous Next 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 Local Variables A variable declared in a function is considered local; that is, it can be referenced solely in that function. Any assignment outside of that function will be considered to be an entirely different variable from the one contained in the function − <?php $x = 4; function assignx () { $x = 0; print “$x inside function is $x. n”; } assignx(); print “$x outside of function is $x. n”; ?> This will produce the following result − $x inside function is 0. $x outside of function is 4. Print Page Previous Next Advertisements ”;

PHP – $_COOKIE

PHP – $_COOKIE ”; Previous Next The PHP superglobal $_COOKIE stores the variables passed to the current PHP script along with the HTTP request in the form of cookies. $HTTP_COOKIE_VARS also contains the same information, but it is not a superglobal, and it has now been deprecated. What is a Cookie? Cookies are text files stored by a server on the client computer and they are kept for tracking purpose. PHP transparently supports HTTP cookies. Cookies are usually set in an HTTP header. JavaScript can also sets a cookie directly on a browser. The server script sends a set of cookies to the browser. It stores this information on the local machine for future use. Next time, when the browser sends any request to the web server, it sends those cookies information to the server and the server uses that information to identify the user. The setcookie() Function PHP provides the setcookie function to create a cookie object to be sent to the client along with the HTTP response. setcookie(name, value, expire, path, domain, security); Parameters Name − Name of the cookie stored. Value − This sets the value of the named variable. Expiry − This specifes a future time in seconds since 00:00:00 GMT on 1st Jan 1970. Path − Directories for which the cookie is valid. Domain − Specifies the domain name in very large domains. Security − 1 for HTTPS. Default 0 for regular HTTP. How to Set Cookies Take a look at the following example. This script sets a cookie named username if it is not already set. Example <?php if (isset($_COOKIE[”username”])) { echo “<h2>Cookie username already set: ” . $_COOKIE[”username”] . “</h2>”; } else { setcookie(“username”, “Mohan Kumar”); echo “<h2>Cookie username is now set.</h2>”; } ?> Run this script from the document root of the Apache server. You should see this message as the output − Cookie username is now set If this script is re-executed, the cookie is now already set. Cookie username already set: Mohan Kumar Example To retrieve cookies on subsequent visit of client − <?php $arr=$_COOKIE; foreach ($arr as $key=>$val); echo “<h2>$key => $val </h2>”; ?> The browser will display the following output − Username => Mohan Kumar How to Remove Cookies To delete a cookie, set the cookie with a date that has already expired, so that the browser triggers the cookie removal mechanism. <?php setcookie(“username”, “”, time() – 3600); echo “<h2>Cookie username is now removed</h2>”; ?> The browser will now show the following output − Cookie username is now removed Setting Cookies Using the Array Notation You may also set the array cookies by using the array notation in the cookie name. setcookie(“user[three]”, “Guest”); setcookie(“user[two]”, “user”); setcookie(“user[one]”, “admin”); If the cookie name contains dots (.), then PHP replaces them with underscores (_). Print Page Previous Next Advertisements ”;

PHP – Call by Reference

PHP – Call by Reference ”; Previous Next PHP uses the “call by value” mechanism, by default, for passing arguments to a function. If the arguments within the function are changed, the changes do not reflect outside of the function. To allow a function to modify its arguments, the “call by reference” mechanism must be used. In PHP, a reference variable acts as an “alias” to the original or host variable so that both of them can read and write a single value. In other words, variables of two different names can access to the same value and they behave as if they are the same variable. The following PHP script will help in understanding what references are. Here, $var is a normal string variable. We declare $var1 as a reference to $var, append “&” symbol to the latter. $var = “Hello”; $var1 = &$var; When we say that $var1 is an alias or reference of $var, it means any change in its value will also change the value of $var, and vice versa. Example The following example demonstrates how “call by reference” works in PHP − <?php $var = “Hello”; $var1 = &$var; $var1 = “Hello World”; echo “var=$var var1=$var1” . PHP_EOL; $var = “How are you?”; echo “var=$var var1=$var1″ . PHP_EOL; ?> It will produce the following output − var=Hello World var1=Hello World var=How are you? var1=How are you? Calling a PHP Function by Reference To call a function by reference, you need to declare the formal arguments with name prefixed by “&” symbol. function callref(&$arg1, &$arg2) { Statements; } The call to the function is just as in “call by value” method. callref($x, $y); When the function is invoked, $arg1 becomes a reference to $x and $arg2 becomes a reference to $y. If, inside the function body, the value of $arg1 or $arg2 (or both) changes, it also causes the values of $x and $y to change. Example Let us have a look at the following example − <?php function change_name(&$nm) { echo “Initially the name is $nm” . PHP_EOL; $nm = $nm.”_new”; echo “This function changes the name to $nm” . PHP_EOL; } $name = “John”; echo “My name is $name” . PHP_EOL; change_name($name); echo “My name now is $name” . PHP_EOL; ?> The variable $name is passed to the function change_name(). A reference variable &$nm becomes its reference variable. Any change in $nm is reflected in $name outside the function. It will produce the following output − My name is John Initially the name is John This function changes the name to John_new My name now is John_new Swapping Two Variables In the following PHP code, we call a function by passing the arguments by value. The function attempts to swap their values. Inside the function, their values are changed, but this swap doesn’t reflect in the actual arguments after the execution of the function. When the same function is called by passing the arguments by reference, the swap effect is reflected in the actual arguments as well. <?php function swap_value($a, $b) { echo “Initial values a = $a b = $b n”; $c = $a; $a = $b; $b = $c; echo “Swapped values a = $a b = $b n”; } $x = 10; $y =20; echo “Actual arguments x = $x y = $y nn”; swap_value($x, $y); echo “Actual arguments do not change after the function: n”; echo “x = $x y = $y nn”; function swap_ref(&$a, &$b) { echo “Initial values a = $a b = $b n”; $c = $a; $a = $b; $b = $c; echo “Swapped values a = $a b = $b n”; } swap_ref($x, $y); echo “Actual arguments get changed after the function: n”; echo “x = $x y = $y”; ?> It will produce the following output − Actual arguments x = 10 y = 20 Initial values a = 10 b = 20 Swapped values a = 20 b = 10 Actual arguments do not change after the function: x = 10 y = 20 Initial values a = 10 b = 20 Swapped values a = 20 b = 10 Actual arguments get changed after the function: x = 20 y = 10 Return by Reference Just as a function in PHP can accept arguments by reference, it can also return a reference. To define a function that returns a reference, prefix the name of the function by “&” symbol. Example The following code shows the example of a function returning a reference. It returns $x, which is a local static variable inside myfunction(). Since “&” symbol is prepended to it, $a (the variable that stores the return value) becomes a reference to &x. As a result, any change in $a will also change the value of $x. <?php function &myfunction(){ static $x=10; echo “x Inside function: $x n”; return $x; } $a=&myfunction(); echo “Returned by Reference: $a n”; $a=$a+10; $a=&myfunction(); ?> It will produce the following output − x Inside function: 10 Returned by Reference: 10 x Inside function: 20 Print Page Previous Next Advertisements ”;

PHP – Decision Making

PHP – Decision Making ”; Previous Next A computer program by default follows a simple input-process-output path sequentially. This sequential flow can be altered with the decision control statements offered by all the computer programming languages including PHP. Decision Making in a Computer Program Decision-making is the anticipation of conditions occurring during the execution of a program and specified actions taken according to the conditions. You can use conditional statements in your code to make your decisions. The ability to implement conditional logic is one of the fundamental requirements of a programming language. A Typical Decision Making Structure Following is the general form of a typical decision making structure found in most of the programming languages − Decision Making Statements in PHP PHP supports the following three decision making statements − if…else statement − Use this statement if you want to execute a set of code when a condition is true and another if the condition is not true. elseif statement − Use this statement with the if…else statement to execute a set of code if one of the several conditions is true switch statement − If you want to select one of many blocks of code to be executed, use the Switch statement. The switch statement is used to avoid long blocks of if..elseif..else code. Almost all the programming languages (including PHP) define the if-else statements. It allows for conditional execution of code fragments. The syntax for using the if-else statement in PHP is similar to that of C − if (expr) statement1 else statement2 The expression here is a Boolean expression, evaluating to true or false Any expression involving Boolean operators such as <, >, <=, >=, !=, etc. is a Boolean expression. If the expression results in true, the subsequent statement – it may be a simple or a compound statement i.e., a group of statements included in pair of braces – will be executed. If the expression is false, the subsequent statement is ignored, and the program flow continues from next statement onwards. The use of else statement is optional. If the program logic requires another statement or a set of statements to be executed in case the expression (after the if keyword) evaluates to false. The elseif statement is a combination of if and else. It allows you to check multiple expressions for TRUE and execute a block of code as soon as one of the conditions evaluates to TRUE. Just like the else statement, the elseif statement is optional. The switch statement is similar to a series of if statements on the same expression. We shall learn about these statements in detail in the subsequent chapters of this tutorial. Print Page Previous Next Advertisements ”;

PHP – Function Parameters

PHP – Function Parameters ”; Previous Next A function in PHP may be defined to accept one or more parameters. Function parameters are a comma-separated list of expressions inside the parenthesis in front of the function name while defining a function. A parameter may be of any scalar type (number, string or Boolean), an array, an object, or even another function. function foo($arg_1, $arg_2, $arg_n) { statements; return $retval; } The arguments act as the variables to be processed inside the function body. Hence, they follow the same naming conventions as any normal variable, i.e., they should start with “$” and can contain alphabets, digits and underscore. Note − There is no restriction on how many parameters can be defined. When a parameterized function needs to be called, you have to make sure that the same number of values as in the number of arguments in function’s definition, are passed to it. foo(val1, val2, val_n); A function defined with parameters can produce a result that changes dynamically depending on the passed values. Example The following code contains the definition of addition() function with two parameters, and displays the addition of the two. The run-time output depends on the two values passed to the function. <?php function addition($first, $second) { $result = $first+$second; echo “First number: $first n”; echo “Second number: $second n”; echo “Addition: $result”; } addition(10, 20); $x=100; $y=200; addition($x, $y); ?> It will produce the following output − First number: 10 Second number: 20 Addition: 30 First number: 100 Second number: 200 Addition: 300 Formal and Actual Arguments Sometimes the term argument is used for parameter. Actually, the two terms have a certain difference. A parameter refers to the variable used in function’s definition, whereas an argument refers to the value passed to the function while calling. An argument may be a literal, a variable or an expression The parameters in a function definition are also often called as formal arguments, and what is passed is called actual arguments. The names of formal arguments and actual arguments need not be same. The value of the actual argument is assigned to the corresponding formal argument, from left to right order. The number of formal arguments defined in the function and the number of actual arguments passed should be same. Example PHP raises an ArgumentCountError when the number of actual arguments is less than formal arguments. However, the additional actual arguments are ignored if they are more than the formal arguments. <?php function addition($first, $second) { $result = $first+$second; echo “First number: $first n”; echo “Second number: $second n”; echo “Addition: $result n”; } # Actual arguments more than formal arguments addition(10, 20, 30); # Actual arguments fewer than formal arguments $x=10; $y=20; addition($x); ?> It will produce the following output − First number: 10 Second number: 20 Addition: 30 PHP Fatal error: Uncaught ArgumentCountError: Too few arguments to function addition(), 1 passed in /home/cg/root/20048/main.php on line 16 and exactly 2 expected in /home/cg/root/20048/main.php:2 Arguments Type Mismatch PHP is a dynamically typed language, hence it doesn’t enforce type checking when copying the value of an actual argument with a formal argument. However, if any statement inside the function body tries to perform an operation specific to a particular data type which doesn’t support it, PHP raises an exception. In the addition() function above, it is assumed that numeric arguments are passed. PHP doesn’t have any objection if string arguments are passed, but the statement performing the addition encounters exception because the “+” operation is not defined for string type. Example Take a look at the following example − <?php function addition($first, $second) { $result = $first+$second; echo “First number: $first n”; echo “Second number: $second n”; echo “Addition: $result”; } # Actual arguments are strings $x=”Hello”; $y=”World”; addition($x, $y); ?> It will produce the following output − PHP Fatal error: Uncaught TypeError: Unsupported operand types: string + string in hello.php:5 However, PHP is a weakly typed language. It attempts to cast the variables into compatible type as far as possible. Hence, if one of the values passed is a string representation of a number and the second is a numeric variable, then PHP casts the string variable to numeric in order to perform the addition operation. Example Take a look at the following example − <?php function addition($first, $second) { $result = $first+$second; echo “First number: $first n”; echo “Second number: $second n”; echo “Addition: $result”; } # Actual arguments are strings $x=”10″; $y=20; addition($x, $y); ?> It will produce the following output − First number: 10 Second number: 20 Addition: 30 Print Page Previous Next Advertisements ”;

PHP – Anonymous Functions

PHP – Anonymous Functions ”; Previous Next What are Anonymous Functions? PHP allows defining anonymous functions. Normally, when we define a function in PHP, we usually provide it a name which is used to call the function whenever required. In contrast, an anonymous function is a function that doesn’t have any name specified at the time of definition. Such a function is also called closure or lambda function. Sometimes, you may want a function for one time use only. The most common use of anonymous functions is to create an inline callback function. Anonymous functions are implemented using the Closure class. Closure is an anonymous function that closes over the environment in which it is defined. The syntax for defining an anonymous function is as follows − $var=function ($arg1, $arg2) { return $val; }; Note that there is no function name between the function keyword and the opening parenthesis, and the fact that there is a semicolon after the function definition. This implies that anonymous function definitions are expressions. When assigned to a variable, the anonymous function can be called later using the variable’s name. Example Take a look at the following example − <?php $add = function ($a, $b) { return “a:$a b:$b addition: ” . $a+$b; }; echo $add(5,10); ?> It will produce the following output − a:5 b:10 addition: 15 Anonymous Function as a Callback Anonymous functions are often used as callbacks. Callback functions are used as one of the arguments of another function. An anonymous function is executed on the fly and its return value becomes the argument of the parent function, which may be either a built-in or a user-defined function. Example In this example, we use an anonymous function inside the usort() function, a built in function that sorts an array by values using a user-defined comparison function. <?php $arr = [10,3,70,21,54]; usort ($arr, function ($x , $y) { return $x > $y; }); foreach ($arr as $x){ echo $x . “n”; } ?> It will produce the following output − 3 10 21 54 70 Example The following example uses an anonymous function to calculate the cumulative sum after successive numbers in an array. Here, we use the array_walk() function. This function applies a user defined function to each element in the array. <?php $arr=array(1,2,3,4,5); array_walk($arr, function($n){ $s=0; for($i=1;$i<=$n;$i++){ $s+=$i; } echo “Number: $n Sum: $s”. PHP_EOL; }); ?> It will produce the following output − Number: 1 Sum: 1 Number: 2 Sum: 3 Number: 3 Sum: 6 Number: 4 Sum: 10 Number: 5 Sum: 15 Anonymous Function as Closure Closure is also an anonymous function that can access the variables outside its scope with the help of the “use” keyword. Example Take a look a the following example − <?php $maxmarks=300; $percent=function ($marks) use ($maxmarks) { return $marks*100/$maxmarks; }; $m = 250; echo “Marks = $m Percentage = “. $percent($m); ?> It will produce the following output − Marks = 250 Percentage = 83.333333333333 Print Page Previous Next Advertisements ”;

PHP – Spaceship Operator

PHP – Spaceship Operator ”; Previous Next The Spaceship operator is one of the many new features introduced in PHP with its 7.0 version. It is a three-way comparison operator. The conventional comparison operators (<, >, !=, ==, etc.) return true or false (equivalent to 1 or 0). On the other hand, the spaceship operator has three possible return values: -1,0,or 1. This operator can be used with integers, floats, strings, arrays, objects, etc. Syntax The symbol used for spaceship operator is “<=>”. $retval = operand1 <=> operand2 Here, $retval is -1 if operand1 is less than operand2, 0 if both the operands are equal, and 1 if operand1 is greater than operand2. The spaceship operator is implemented as a combined comparison operator. Conventional comparison operators could be considered mere shorthands for <=> as the following table shows − Operator <=> equivalent $a < $b ($a <=> $b) === -1 $a <= $b ($a <=> $b) === -1 || ($a <=> $b) === 0 $a == $b ($a <=> $b) === 0 $a != $b ($a <=> $b) !== 0 $a >= $b ($a <=> $b) === 1 || ($a <=> $b) === 0 $a > $b ($a <=> $b) === 1 Example 1 The following example shows how you can use the spaceship operator in PHP − <?php $x = 5; $y = 10; $z = $x <=> $y/2; echo “$x <=> $y/2 = $z”; ?> It will produce the following output − 5 <=> 10/2 = 0 Example 2 Change $x=4 and check the result − <?php $x = 4; $y = 10; $z = $x <=> $y/2; echo “$x <=> $y/2 = $z”; ?> It will produce the following output − 4 <=> 10/2 = -1 Example 3 Change $y=7 and check the result again − <?php $x = 7; $y = 10; $z = $x <=> $y/2; echo “$x <=> $y/2 = $z”; ?> It will produce the following output − 7 <=> 10/2 = 1 Example 4 When used with string operands, the spaceship operand works just like the strcmp() function. <?php $x = “bat”; $y = “ball”; $z = $x <=> $y; echo “$x <=> $y = $z”; ?> It will produce the following output − bat <=> ball = 1 Example 5 Change $y = “baz” and check the result − <?php $x = “bat”; $y = “baz”; $z = $x <=> $y; echo “$x <=> $y = $z”; ?> It will produce the following output − bat <=> baz = -1 Spaceship Operator with Boolean Operands The spaceship operator also works with Boolean operands − true <=> false returns 1 false <=> true returns -1 true <=> true as well as false <=> false returns 0 Print Page Previous Next Advertisements ”;

PHP – Heredoc & Nowdoc

PHP – Heredoc & Nowdoc ”; Previous Next PHP provides two alternatives for declaring single or double quoted strings in the form of heredoc and newdoc syntax. The single quoted string doesn’t interpret the escape characters and doesn’t expand the variables. On the other hand, if you declare a double quoted string that contains a double quote character itself, you need to escape it by the “” symbol. The heredoc syntax provides a convenient method. Heredoc Strings in PHP The heredoc strings in PHP are much like double-quoted strings, without the double-quotes. It means that they don’t need to escape quotes and expand variables. Heredoc Syntax $str = <<<IDENTIFIER place a string here it can span multiple lines and include single quote ” and double quotes “ IDENTIFIER; First, start with the “<<<” operator. After this operator, an identifier is provided, then a newline. The string itself follows, and then the same identifier again to close the quotation. The string can span multiple lines and includes single quotes (‘) or double quotes (“). The closing identifier may be indented by space or tab, in which case the indentation will be stripped from all lines in the doc string. Example The identifier must contain only alphanumeric characters and underscores and start with an underscore or a non-digit character. The closing identifier should not contain any other characters except a semicolon (;). Furthermore, the character before and after the closing identifier must be a newline character only. Take a look at the following example − <?php $str1 = <<<STRING Hello World PHP Tutorial by TutorialsPoint STRING; echo $str1; ?> It will produce the following output − Hello World PHP Tutorial by TutorialsPoint Example The closing identifier may or may not contain indentation after the first column in the editor. Indentation, if any, will be stripped off. However, the closing identifier must not be indented further than any lines of the body. Otherwise, a ParseError will be raised. Take a look at the following example and its output − <?php $str1 = <<<STRING Hello World PHP Tutorial by TutorialsPoint STRING; echo $str1; ?> It will produce the following output − PHP Parse error: Invalid body indentation level (expecting an indentation level of at least 16) in hello.php on line 3 Example The quotes in a heredoc do not need to be escaped, but the PHP escape sequences can still be used. Heredoc syntax also expands the variables. <?php $lang=”PHP”; echo <<<EOS Heredoc strings in $lang expand vriables. The escape sequences are also interpreted. Here, the hexdecimal ASCII characters produce x50x48x50 EOS; ?> It will produce the following output − Heredoc strings in PHP expand vriables. The escape sequences are also interpreted. Here, the hexdecimal ASCII characters produce PHP Nowdoc Strings in PHP A nowdoc string in PHP is similar to a heredoc string except that it doesn’t expand the variables, neither does it interpret the escape sequences. <?php $lang=”PHP”; $str = <<<”IDENTIFIER” This is an example of Nowdoc string. it can span multiple lines and include single quote ” and double quotes “ IT doesn”t expand the value of $lang variable IDENTIFIER; echo $str; ?> It will produce the following output − This is an example of Nowdoc string. it can span multiple lines and include single quote ” and double quotes “ IT doesn”t expand the value of $lang variable The nowdoc’s syntax is similar to the heredoc’s syntax except that the identifier which follows the “<<<” operator needs to be enclosed in single quotes. The nowdoc’s identifier also follows the rules for the heredoc identifier. Heredoc strings are like double-quoted strings without escaping. Nowdoc strings are like single-quoted strings without escaping. Print Page Previous Next Advertisements ”;