0% found this document useful (0 votes)
3 views58 pages

Unit 2 - PHP Functions

it is unit 2 php function

Uploaded by

shahnishi7700
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views58 pages

Unit 2 - PHP Functions

it is unit 2 php function

Uploaded by

shahnishi7700
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

PHP Functions

Contents
 Learning Outcomes
 Functions in PHP
 Function Arguments in PHP
 PHP String Functions
 PHP Math Functions
 PHP Date/Time Functions
 PHP Common Functions
 Variable Scopes

2 (RCTI) 2 February 2025


Functions in PHP
 A function is a block of statements that can be used repeatedly in a
program.

 A function will NOT execute automatically when a page loads. It needs to


be called out to be executed.

 PHP has over 1000 built-in functions that can be called directly, from
within a script, to perform a specific task.

 Besides the built-in functions, it is possible to create your own functions.

4 (RCTI) 2 February 2025


Advantages of function:-

 Function reduces the repetition of code within a program.


 Function makes the code much easier to maintain.
 Function makes it easier to eliminate the errors.
 Function can be reused in other application.

5 (RCTI) 2 February 2025


Functions in PHP
 The functions that are defined by a developer/user are called User-defined Functions
and are created by using function keyword as below:

 Syntax:
function functionname(arguments if any)
{
//code to be executed
}

 New concept in PHP: Functions in PHP don’t have a return type, because we don’t
need to mention the datatype of the returning value.

 A function name must start with a letter or an underscore. Function names are NOT
case-sensitive. Functions can return values.

6 (RCTI) 2 February 2025


Functions in PHP
 Example 1 (Without Arguments, Without Return Value):
function testprint() {
echo “Hello World”;
}
testprint();  Function call  Output: Hello World

 Example 2 (With Arguments, Without Return Value):


function add($x, $y) {
echo “Addition = ” . ($x + $y);
}
add(10, 12);  Output: 22  $x and $y arguments take values 10 and 12.

7 (RCTI) 2 February 2025


Functions in PHP
 Example 3 (Without Arguments, With Return Value):
function calc() {
return (5 ** 2);
}
echo calc();  Output: 25

 Example 4 (With Arguments, With Return Value):


function div($x, $y)
{
return ($x / $y);
}
echo div(5, 2);  Output: 2.5

8 (RCTI) 2 February 2025


Function Arguments in PHP
 Just like other programming languages, there are 2 types of arguments in
any function in PHP:
1. Formal/Temporary/Dummy Arguments
2. Actual Arguments

 Formal arguments are created when defining the function, while Actual
arguments are those that are actually passed in a function call.

 Formal arguments are just a representation of the actual arguments,


while the task is performed on the actual arguments.

9 (RCTI) 2 February 2025


Function Arguments in PHP
function calc($a, $b) {  Function Definition
$c = $a + $b;
echo ‘Addition = ‘ . $c;
}
calc(10, 20);  Function Call

 In the above example, $a and $b are formal arguments, while 10 and 20 are the
actual arguments.

 Here, addition inside the function is performed on 10 and 20 (which are copied
in $a and $b during function execution).

10 (RCTI) 2 February 2025


Function Arguments in PHP
 The arguments can be passed to the function in 2 ways as follows:
1. Pass by Value
2. Pass by Reference

 Pass by Value:
 Normally, the arguments are passed by value, which means that a copy of the
value is used in the function.

 Since the operations inside the function are performed on this copy, the value
of the passed variable remains unchanged outside the function.

11 (RCTI) 2 February 2025


Function Arguments in PHP(pass by value)
 Example:
<?php
function swap($x, $y) //formal argument
{ $temp = $x;
$x = $y;
$y = $temp;
echo "The value of x is:".$x."<br>";
echo "The value of y is:".$y."<br><br>";
}
$a = 10;
$b = 20;
swap($a, $b); //actual argument
echo "The value of a is :".$a."<br>";
echo "The value of b is :".$b."<br>";
?>
Here, values of actual arguments $a and $b remain 10 and 20 respectively even after calling swap function, as the
swapping is done on the copies of $a & $b, and the not the original variables that were passed.(the calling function
arguments and the called function argument will be represented in different memory locations.)

12 (RCTI) 2 February 2025


Function Arguments in PHP
 Pass by Reference:
 If arguments are passed by reference, then the original (actual) arguments
are passed to the function, instead of their copies.

 Hence, any changes/operations done on the passed variables inside the


function are retained even outside the function (after the function call).

 To turn a function argument into a reference i.e. to pass an argument by


reference, the ‘&’ operator is used before the formal argument name.

13 (RCTI) 2 February 2025


Function Arguments in PHP(pass by reference)
 Example:
<?php
function swap(&$x, &$y)
{ $temp = $x;
$x = $y;
$y = $temp;
echo "The value of x is: ".$x."<br>";
echo "The value of y is: ".$y."<br><br>";
}
$a = 10;
$b = 20;
swap($a, $b);
echo "The value of a is: ".$a."<br>";
echo "The value of b is: ".$b."<br>";
?>

 Here, values of actual arguments $a and $b change to 20 and 10 respectively after calling swap function, as swapping is
done on the original variables that were passed.(both the arguments of the calling function and the called function
represent the same memory location.)

14 (RCTI) 2 February 2025


Function Arguments in PHP
 Formal arguments can also be provided default values at the time of
creating (defining) a function.

 In such case, the arguments having default values in declaration become


optional during the function call.

 More than 1 arguments can be made optional by giving default values;


however all such arguments should be mentioned at last in the
arguments list.

15 (RCTI) 2 February 2025


Function Arguments in PHP
 Syntax:
function functionname(arg1, arg2 = value)
{…
}

 Example:
function test($x, $y = 10, $z = 15)
{
echo “x = $x, y = $y, z = $z”;
}
test(5);  Output: x = 5, y = 10, z = 15
test(1, 8);  Output: x = 1, y = 8, z = 15
test(2, 5, 7);  Output: x = 2, y = 5, z = 7

16 (RCTI) 2 February 2025


Variable function in PHP
 Variable functions allow you to use a variable like a function.
 When you append parentheses () to a variable, PHP will look for the function
whose name is the same as the value of the variable and execute it.
 This feature is useful in implementing callbacks mechanisms, function tables
etc.
 Example:
<?php
function hello()
{
echo "Hello World";
}
$var=“hello"; // The variable should hold the function name
$var(); // This will call the hello() function
?> o/p: Hello World
17 (RCTI) 2 February 2025
 Ex:-
<?php
function add($x, $y)
{
echo $x+$y;
}
$var="add";
$var(10,20);
?>
o/p:- 30

18 (RCTI) 2 February 2025


19 Using PHP built-in function

String processing functions


Mathematical functions
Date/Time function

(RCTI) 2 February 2025


20 String Functions
 chr()  Str_split()
 Ord()  Str_word_count
 Strlen()  Strcmp()
 Strcasecmp()
 Trim()
 Strops()
 Ltrim()
 Stripos()
 Rtrim()
 Strrev()
 Join()
 Strtolower()
 Substr()  Strtoupper()
 Str_replace()  Str_shuffle

(RCTI) 2 February 2025


String Functions
21  Chr( )  ord()
 Returns a character from a specified  Returns the ASCII value of the first
ASCII value
character of a string
 Syntax
 Syntax
chr(ascii)
ord(string)
<?php
echo chr(52) . "<br>"; // Decimal value <?php
echo chr(052) . "<br>"; // Octal value echo ord("h")."<br>";
echo chr(0x52) . "<br>"; // Hex value echo ord("hello")."<br>";
?> ?>
o/p: o/p:
4 104
*
R 104

(RCTI) 2 February 2025


String Functions
22
 strlen()  trim()
 Return the length of the string  Removes whitespace or other characters from
both sides of a string
 Syntax
 Syntax
strlen(string)
trim(string,charlist)

<?php
<?php
echo strlen("Hello"); $str = “ Hello world “; <?php
?> echo trim($str); $str = "xxHello worldxx";
o/p: ?>
echo trim($str, "x");
5
o/p: ?>
Hello world

(RCTI) 2 February 2025


String Functions
23  ltrim()  rtrim()
 Removes whitespace or other  Removes whitespace or other
predefined characters from the left predefined characters from the right
side of a string side of a string
 Syntax  Syntax
ltrim(string,charlist) rtrim(string,charlist)

<?php <?php
$str = "Hello World"; $str = "Hello World";
echo $str . "<br>"; echo $str . "<br>";
echo ltrim($str,"Hello"); echo rtrim($str,"World");
?> ?>
o/p: o/p:
Hello World Hello World
World Hello
(RCTI) 2 February 2025
String Functions
24
 ltrim()  rtrim()
<?php <?php
$str = "xxHello worldxx"; $str = "xxHello worldxx";
echo ltrim($str, "x"); echo rtrim($str, "x");
?> ?>
o/p:Hello worldxx
o/p: xxHello world

(RCTI) 2 February 2025


String Functions
25  join()  substr()
 The join() function returns a string  The substr() function in PHP returns a
from the elements of an array portion of a string ,starting from a
specified position, with an optional
 Syntax length.
join(separator,array)  Syntax
substr(string,start,length)
<?php <?php
$arr = echo substr("Hello world",6) ."<br>";
array('Hello','World!','Beautiful','Day!'); echo substr("Hello world",1,8)."<br>";
echo join(" ",$arr)."<br>"; echo substr("Hello world",0,5)."<br>";
echo join("+",$arr)."<br>"; ?>
?> o/p:
World
o/p: ello wor
Hello World! Beautiful Day! Hello
Hello+World!+Beautiful+Day!
(RCTI) 2 February 2025
String Functions
26  Str_replace()  Str_split()
 Replaces some characters in a string
(case-sensitive)  Splits a string into an array
 Syntax  Syntax
str_replace(find,replace, str_split(string,length)
string,count)
<?php
<?php print_r(str_split("Hello"));
$arr = array("blue","red","green","yellow"); print_r(str_split("Hello",3));
print_r(str_replace("red","pink",$arr,$i));
?>
echo "<br>" . "Replacements: $i";
o/p:
?>
o/p: Array ( [0] => H [1] => e [2] => l [3] => l
Array ( [0] => blue [1] => pink [2] => green [3] [4] => o )
=> yellow )
Replacements: 1 Array ( [0] => Hel [1] => lo )
2 February 2025

(RCTI)
String Functions
27  Str_word_cont() o/p:
 Count the number of words in a string 2
 Syntax
str_word_count(string,return,char) Array ( [0] => Hello [1] => world
[2] => good [3] => morning )
<?php
echo str_word_count("Hello world!");
print_r(str_word_count("Hello world & good Array ( [0] => Hello [6] => world
morning!",1)); //Returns an indexed array of words. [14] => good [19] => morning )
print_r(str_word_count("Hello world & good
morning!",2)); // Returns an associative array with
positions Array ( [0] => Hello [1] => world
[2] => Ho [3] => w [4] => are [5]
print_r(str_word_count("Hello, world! Ho?w are => you
you?", 1, " ,!?"));
?>
2 February 2025
(RCTI)
String Functions
28
 Strcmp() Return Values:
 Compares two strings (case-sensitive) 0: If the strings are equal.

 Syntax < 0: If string1 is less than string2.


strcmp(string1,string2) > 0: If string1 is greater than
string2.
<?php
echo strcmp("Hello world!","Hello world!");
?>
<p>If this function returns 0, the two strings
are equal.</p>
o/p:
0

2 February 2025
(RCTI)
String Functions
29
 strcasecmp()  strrev()
 Compares two strings (case-  Reverses a string
insensitive)
Syntax
 Syntax strrev(string)
strcasecmp(string1,string2)
<?php
<?php
echo strcasecmp("Hello","HELLO");
echo "<br>";
echo strrev("Hello World!");

echo strcasecmp("Hello","hELLo"); ?>


?> o/p:
o/p: !dlroW olleH

0
2 February 2025
0
String Functions
30
 Strpos()  Stripos()
 Returns the position of the first  Returns the position of the first
occurrence of a string inside another
string (case-sensitive) occurrence of a string inside
 Syntax
another string (case-insensitive)
strpos(string,find,start)  Syntax
<?php stripos(string,find,start)
$str = "Hello World!"; <?php
echo strpos($str, "World"); $str = "Hello World!";
?> o/p: 6 echo stripos($str, "world”);
<?php ?> o/p: 6
$str = "Hello World!";
echo strpos($str, "world");
2 February 2025
?> o/p: false
String Functions
31
 strtolower()  Strtoupper()
 Converts a string to lowercase  Converts a string to uppercase letters
letters  Syntax
 Syntax strtoupper(string)
strtolower(string)
<?php
<?php echo strtoupper("Hello WORLD!");
echo strtolower("Hello WORLD."); ?>
?> o/p:
o/p: HELLO WORLD!

hello world.
2 February 2025
String Functions
32
 Str_shuffle()
 Randomly shuffles all characters in
a string
 Syntax
str_shuffle(string)
<?php
echo str_shuffle("Hello World");
<p>Try to refresh the page. This function
will randomly shuffle all characters each
time.</p>
?>
o/p:
olrW loHled 2 February 2025
Math Functions
33
 abs()  exp()
 ceil()  log()
 Floor()  decbin()
 Round()  Decoct()
 Rand()  Dechex()
 Min()  Sin()
 Max()  Cos()
 Pi()  Tan()
 Pow()  deg2rad()
 Sqrt()  Rad2deg()
2 February 2025
math Functions
34  abs()  ceil()
 The abs() function returns the absolute  The ceil() function rounds a number UP to
(positive) value of a number. the nearest integer, if necessary.
 Syntax  Syntax
abs(number); ceil(number);

<?php <?php
echo(ceil(0.60) . "<br>");
echo(abs(6.7) . "<br>");
echo(ceil(0.40) . "<br>");
echo(abs(-6.7) . "<br>");
echo(ceil(5) . "<br>");
echo(abs(-3) . "<br>");
echo(ceil(5.1) . "<br>");
echo(abs(3)); echo(ceil(-5.1) . "<br>");
?> ?>
o/p: o/p:
6.7 1
6.7 1
3 5
3 6
2 February 2025
-5
math Functions
35  floor()  round()
 The floor() function rounds a number  The round() function rounds a floating-point
DOWN to the nearest integer, if number.
necessary, and returns the result.
 Syntax
 Syntax
round(number,precision,mode);
floor(number);
<?php
<?php
echo(floor(0.60) . "<br>");
echo(round(0.60) . "<br>");
echo(floor(0.40) . "<br>"); echo(round(0.50) . "<br>");
echo(floor(5) . "<br>"); echo(round(0.49) . "<br>");
echo(floor(5.1) . "<br>"); echo(round(-4.40) . "<br>");
echo(floor(-5.1) . "<br>"); ?>
?> o/p:
o/p:
1
0 1
0 0
5
5 -4
-6 2 February 2025
math Functions
36  rand()  pi()
 The rand() function generates a
random integer.  The pi() function returns the value
 Syntax of PI.
rand();  Syntax
or
rand(min,max); pi();
<?php
<?php
echo(rand() . "<br>");
echo(rand() . "<br>"); echo(pi());
echo(rand(10,100)); ?>
?>
o/p: o/p:
512549293 3.1415926535898
1132363175
79 2 February 2025
math Functions
37  min()  max()
 The min() function returns  The max() function returns the highest
the lowest value in an value in an array, or the highest value
of several specified values.
array, or the lowest value of
several specified values.  Syntax
max(array_values);
Syntax or
min(array_values); max(value1,value2,...);
or <?php
min(value1,value2,...); echo(max(22,14,68,18,15) . "<br>");
<?php echo(max(array(4,6,8,10)) . "<br>");
echo(min(22,14,68,18,15) . "<br>");
?>
echo(min(array(4,6,8,10)) . "<br>");
o/p:
?>
o/p:
68
10
14
2 February 2025
4
math Functions
38
 sqrt()  pow()
 The sqrt() function returns  The pow() function returns x raised
to the power of y.
the square root of a number.
 Syntax
 Syntax
pow(x,y);
sqrt(number);
<?php
echo(sqrt(1) . "<br>"); <?php
echo(pow(2,4) . "<br>");
echo(sqrt(9) . "<br>");
echo(pow(-2,4) . "<br>");
echo(sqrt(0.64) . "<br>");
echo(pow(-2,-4) . "<br>");
?> ?>
o/p: o/p:
1 16
3 16
0.8 0.0625
2 February 2025
math Functions  log()
39
 exp()  The log() function returns the natural logarithm of a
number, or the logarithm of number to base.
 The exp() function returns E raised to the
power of x (Ex).  Syntax
log(number,base);
 Syntax
<?php
exp(x);
echo(log(2.7183) . "<br>");
<?php echo(log(2) . "<br>");
echo(exp(0) . "<br>"); echo(log(1) . "<br>");
echo(exp(1) . "<br>"); echo(log(0));
echo(exp(10) . "<br>"); echo log(10, 2); //calculates the logarithm of 10 to base 2.
echo(exp(4.8)); ?>
?> o/p:

o/p: 1.000006684914
0.69314718055995
1 0
2.718281828459 -INF
22026.465794807 3.321
121.51041751873 2 February 2025
math Functions
40
 decbin()  decoct()
 The decbin() function converts a  The decoct() function converts a
decimal number to a binary number.
decimal number to an octal number.
 Syntax
 Syntax
decbin(number);
<?php decoct(number);
echo decbin("3") . "<br>";
<?php
echo decbin("1") . "<br>"; echo decoct("30") . "<br>";
echo decbin("7"); echo decoct("10") . "<br>";
?>
?>
o/p:
o/p:
11
1 36
111
12 2 February 2025
math Functions
41
 dechex()  sin()
 The dechex() function converts a  The sin() function returns the sine of a
decimal number to a hexadecimal number.
number.  Syntax
 Syntax sin(number);
dechex(number); <?php
<?php echo(sin(3) . "<br>");
echo dechex("1587") . "<br>"; echo(sin(-3) . "<br>");
echo dechex("70"); echo(sin(0) . "<br>");

?>
?>
o/p:
o/p:
0.14112000805987
633 -0.14112000805987 2 February 2025
46 0
math Functions
42
 cos()  tan()
 The cos() function returns the cosine  The tan() function returns the tangent of a
of a number. number.
 Syntax  Syntax
cos(number); tan(number);
<?php <?php
echo(cos(3) . "<br>"); echo(tan(10) . "<br>");
echo(cos(-3) . "<br>"); echo(tan(-5) . "<br>");
echo(cos(0) . "<br>"); echo(tan(-10));
?> ?>
o/p: o/p:
-0.98999249660045 0.64836082745909
-0.98999249660045 3.3805150062466 2 February 2025
1 -0.64836082745909
math Functions
43
 deg2rad()  rad2deg()
 The deg2rad() function converts a degree  The rad2deg() function converts a radian
value to a radian value.
value to a degree value.
 Syntax
 Syntax
deg2rad(number);
rad2deg(number);
<?php
echo deg2rad("45") . "<br>"; <?php
echo deg2rad("90") . "<br>"; echo rad2deg(pi()) . "<br>";
echo deg2rad("360");
echo rad2deg(pi()/4);
??>
o/p:
?>?>
0.78539816339745 o/p:
1.5707963267949 180
6.2831853071796
45 2 February 2025
Date/Time Functions
Sr. No. Function Syntax Description
1 checkdate( ) checkdate(month, day, year) Validates whether a date exists
date_add( ) / date_add(object, interval) / Adds / Subtracts days, months, years, hours,
2, 3
date_sub( ) date_sub(object, interval) minutes, and seconds to / from a date
4 date_create( ) date_create(time, timezone) Returns a new DateTime object
date_diff(datetime1,
5 date_diff( ) Returns the difference between two dates
datetime2, absolute)
Returns a date formatted according to a specified
6 date_format( ) date_format(object, format)
format
7 date( ) date(format, timestamp) Returns formatted local date and time
Returns date & time information (in an array) of a
8 getdate( ) getdate(timestamp)
timestamp or the current local date & time

44 (RCTI) 2 February 2025


Date/Time Functions
Sr. No. Function Syntax Description
9 localtime( ) localtime(timestamp, is_assoc) Returns the local time (in an array format)
mktime(hour, minute, second,
10 mktime( ) Returns the Unix timestamp for a date
month, day, year, is_dst)
Parses an English textual date-time into a Unix
11 strtotime( ) strtotime(time, now);
timestamp
12 time() time() Returns the current time as a Unix timestamp

45 (RCTI) 2 February 2025


Common Functions
Sr. No. Function Syntax Description
1 isset( ) isset(variable_name) Checks whether a variable is set (declared & not NULL)
2 empty( ) empty(variable_name) Checks whether a variable is empty
3 unset( ) unset(variable_name) Unsets a variable (i.e. deletes its value)
4 include( ) include(filename) Includes specified file in another file
5 include_once( ) include_once(filename) Includes specified file in another file only once
Includes specified file in another file & generates error
6 require( ) require(filename)
if included file is not found
7 die( ) die(message) Print a message and terminate (end) the current script
8 exit( ) exit(message) Same as die()

46 (RCTI) 2 February 2025


Variable Scopes
 The scope of a variable is the part of the script/code where the variable
can be referenced/used.

 PHP has three different variable scopes depending on where the variables
are declared in the script:

1. Local
2. Global
3. Static

47 (RCTI) 2 February 2025


Local Scope
 A variable declared within a function has a local scope and can only be
accessed within that function.

 Example:
function test() {
$x = 5;  local variable
echo $x;
}
test();  Output: 5
echo $x;  using local variable outside the function shows ERROR

48 (RCTI) 2 February 2025


Global Scope
 A variable declared outside a function has a global scope and can only be
accessed outside a function.

 Example:
$x = 5;  global variable
function test() {
echo $x;  using global variable inside function shows ERROR
}
test();
echo $x;  Output: 5

49 (RCTI) 2 February 2025


The ‘global’ Keyword
 A global variable can still be accessed from within a function using the
global keyword before the variable name (inside the function).

 Example:
$x = 5; $y = 10;  global variables
function test() {
global $x, $y;  Access to global variables inside function
echo “$x, $y”;  NO ERROR
}
test();  Output: 5, 10

50 (RCTI) 2 February 2025


Using $GLOBALS
 PHP also stores all global variables in a super global array called $GLOBALS[index].
Here, index holds the name of the variable without $.

 This array is also accessible from within the functions and can be used to update global
variables directly.

 Example:
$x = 5; $y = 10;
function test() {
$GLOBALS[‘z'] = $GLOBALS['x'] + $GLOBALS['y'];
}
test();
echo $z;  Output: 15

51 (RCTI) 2 February 2025


Static Scope
 Normally, when a function is completed/executed, all of its (local)
variables are deleted.

 However, if we want a variable NOT to be deleted after the function has


completed executing, that variable is declared with static scope.

 static keyword is used to declare a variable with static scope.

 A static variable and its value are retained even after the function has
completed its execution.

52 (RCTI) 2 February 2025


Static Scope
 Example:
function test() {
static $x = 0;  static variable initialized only in 1st function call
echo $x;
$x++;  Value of same static variable $x is incremented every time
}
test();  Output: 0
test();  Output: 1
test();  Output: 2

 Note: In above example, static variable $x is still local to the function test().

53 (RCTI) 2 February 2025


PHP strings: single quoted vs double quoted

54 (RCTI) 2 February 2025


PHP heredoc syntax
 Heredoc is a way to define a string that spans multiple lines. The string
can contain variables, and those variables will be parsed (evaluated)
inside the string.
 Syntax:
<<< IDENTIFIER
//content
IDENTIFIER;
$str=<<< IDENTIFIER echo<<< IDENTIFIER
//content //content
IDENTIFIER; IDENTIFIER;
echo $str;

55 (RCTI) 2 February 2025


Ex:-
$name ='John’; o/p:
$age = 30; My name is John.
$text = <<<EOD I am 30 years old.;
My name is $name.
I am $age years old.
EOD;
echo $text;

*EOD (End of Document) is the identifier, and you can choose any label (but EOD is commonly used).
56 (RCTI) 2 February 2025
PHP nowdoc syntax
 Nowdoc is similar to heredoc, but it does not parse variables inside the
string. The string is treated as plain text, including any $ characters.
 Syntax:
<<<‘ IDENTIFIER’
//content
IDENTIFIER;
$str=<<< ‘IDENTIFIER’ echo<<< ‘IDENTIFIER’
//content //content
IDENTIFIER; IDENTIFIER;
echo $str;

57 (RCTI) 2 February 2025


Ex:-
$name = 'John’;
o/p:
$age = 30;
My name is $name.
$text = <<<'EOD’
I am $age years old.
My name is $name.
I am $age years old.
EOD;
echo $text;

58 (RCTI) 2 February 2025


Key Differences:
 Heredoc allows variable interpolation (variables are parsed).
 Nowdoc does not allow variable interpolation (variables are treated as
plain text).
Use Cases:
 Use heredoc when you need to include variables in a large block of text.
 Use nowdoc when you need a block of text that should not evaluate any
variables (e.g., when working with SQL queries, code snippets, or any raw
text).

59 (RCTI) 2 February 2025


THANK YOU

60 (RCTI) 2 February 2025

You might also like