UNIT III - Functions in PHP
UNIT III - Functions in PHP
1) Code reusability: PHP functions are defined only once and can be invoked
many times, like in other programming languages.
Creating a Function
While creating a user defined function we need to keep few things in mind:
Syntax:
function function_name(){
executable code;
}
Function definitions begin with the function keyword, followed by the function
name and a list of arguments (optional) in parentheses. Curly braces then
enclose the main body of the function, which can contain any legal PHP code,
including variable definitions, conditional tests, loops, and output statements.
function myMessage() {
To call the function, just write its name followed by parentheses ():
function myMessage() {
myMessage();
Example
<?php
function sayHello(){
echo "Hello PHP Function";
}
sayHello(); //calling function
?>
Output:
<?php
function cube($n){
return $n*$n*$n;
}
echo "Cube of 3 is: ".cube(3);
?>
Output:
Cube of 3 is: 27
Call by Value
On passing arguments using pass by value, the value of the argument gets
changed within a function, but the original value outside the function remains
unchanged. That means a duplicate of the original value is passed as an
argument.
Output:
Hello Sonoo
Hello Vimal
Hello John
<?php
function sayHello($name,$age){
echo "Hello $name, you are $age years old<br>";
}
sayHello("Sonoo",27);
sayHello("Vimal",29);
sayHello("John",23);
?>
Output:
Hello Sonoo, you are 27 years old
Hello Vimal, you are 29 years old
Hello John, you are 23 years old
Call by Reference
By default, value passed to the function is call by value. Value passed to the
function doesn't modify the actual value.
<?php
function adder(&$str2)
{
$str2 .= 'Call By Reference';
}
$str = 'Hello ';
adder($str);
echo $str;
?>
Output:
Hello Call By Reference
Output:
Hello Rajesh
Hello Sonoo
Hello John
A PHP function definition normally has a fixed argument list, where the number
of arguments is known in advance. However, PHP allows to define functions
with so-called variable-length argument lists or dynamic argument list, where
the number of arguments can change with each invocation of the function.
By using the ... operator in front of the function parameter, the function
accepts an unknown number of arguments. This is also called a variadic
function. The variadic function argument becomes an array.
Example A function that do not know how many arguments it will get
<?php
function sumMyNumbers(...$x) {
$n = 0;
$len = count($x);
$n += $x[$i];
}
return $n;
$a = sumMyNumbers(5, 2, 6, 2, 7, 7);
echo $a;
?>
Output:
29
<?php
function calcAverage() {
$args = func_get_args();
$count = func_num_args();
$sum = array_sum($args);
return $avg;
echo calcAverage(3,6,9);
echo calcAverage(100,200,100,300,50,150,250,50);
?>
The calcAverage() function definition does not include a predefined argument
list; rather, the arguments passed to it are retrieved at run time using the
func_num_args() and func_get_args() functions.
print()
PHP echo and print Statements
There are two basic ways to get output: echo and print. They
are used to output data to the screen. They can be used with or
without parentheses.
echo and print are more or less the same. The differences are small:
Display Variables
!DOCTYPE html>
<html>
<body>
<?php
$txt1 = "Learn PHP";
$txt2 = "W3Schools.com";
$x = 5;
$y = 4;
echo "<h2>" . $txt1 . "</h2>";
echo "Study PHP at " . $txt2 . "<br>";
echo $x + $y;
?>
</body>
</html>
Output
Learn PHP
Study PHP at W3Schools.com
9
The PHP print Statement
The print statement can be used with or without
parentheses: print or print().
Display Text
Example
<html>
<body>
<?php
print "<h2>PHP is Fun!</h2>";
print "Hello world!<br>";
print "I'm about to learn PHP!";
?>
</body>
</html>
Output
PHP is Fun!
Hello world!
I'm about to learn PHP!
Display Variables
Example
<!DOCTYPE html>
<html>
<body>
<?php
$txt1 = "Learn PHP";
$txt2 = "W3Schools.com";
$x = 5;
$y = 4;
print "<h2>" . $txt1 . "</h2>";
print "Study PHP at " . $txt2 . "<br>";
print $x + $y;
?>
</body>
</html>
Output
Learn PHP
Study PHP at W3Schools.com
9
<?php
$fname = "Gunjan";
$lname = " Gunjan ";
echo "My name is: ".$fname,$lname;
?>
Output:
<?php
$fname = "Gunjan";
$lname = "Garg";
print "My name is: ".$fname,$lname;
?>
Output:
echo statement does not return any value. It will generate an error if
you try to display its return value.
<?php
$lang = "PHP";
$ret = echo $lang." is a web development language.";
echo "<br>";
echo "Value return by print statement: ".$ret;
?>
Output:
<?php
$lang = "PHP";
$ret = print $lang." is a web development language.";
print "<br>";
print "Value return by print statement: ".$ret;
?>
Output:
header()
The header() is a pre-defined network function of PHP, which sends
a raw HTTP header to a client. Headers facilitate communication
between the server and the client's web browser, enabling the exchange
of information and instructions. Headers should be set before any output
is sent to the browser, ensuring they are sent in the initial response from
the server. i.e The header() function must be called before sending any
actual output. With header() HTTP functions we can control data sent to
the client or browser by the web server before some other output has
been sent.
PHP Changelog
PHP 4.0.2: The header() function was introduced in PHP 4.0.2.
PHP 4.3.0: Before PHP 4.3.0, the header() function had a limitation that it
could only be called before any actual output was sent to the browser. If
the output was already sent, calling header() would result in a warning.
Starting from PHP 4.3.0, this limitation was relaxed, and it became
possible to use header() after output had been sent, as long as no output
had been flushed to the browser yet.
PHP 5.1.0: In PHP 5.1.0, the header() function gained an optional third
parameter $http_response_code. This parameter allows specifying the
HTTP response code directly when setting headers. Before this version,
the response code had to be set using a separate function, such
as http_response_code().
PHP 7.0.0: In PHP 7.0.0, the header() function was made case-insensitive,
meaning that the header names are no longer required to be in a specific
case. This change was made to align with HTTP specification
requirements.
Syntax
The syntax of the header() function is as follows:
void header(string $header, bool $replace = true, int $http_response_code )
The header() function in PHP is used to send an HTTP header to the browser.
Here is an explanation of the parameters:
Parameter Values
The header() function in PHP allows you to set various parameter values to control
the behavior and characteristics of the HTTP response. Here are some commonly
used parameter values:
Content-Type:
Specifies the type of the content being sent. Common values include text/html
for HTML content, application/json for JSON content, image/jpeg for JPEG
images, etc. Location
Used for redirecting the user to a different URL. The value should be a valid
URL to which the user will be redirected.
Cache-Control:
Example: header('Cache-Control: no-cache, no-store')
Expires:
Specifies the expiration date and time for the content being sent. It helps in
caching and instructs the browser when to consider the content as expired.
Content-Disposition:
Used for specifying the behavior of the content being sent. For example, an
attachment suggests that the content should be treated as a file attachment,
and a filename specifies the name of the file.
Response Code:
Sets the HTTP response code for the current request. Common codes include
200 OK, 404 Not Found, 500 Internal Server Error, etc.
<?php
header('Content-Type: text/plain');
header('X-Custom-Header: Hello, world!');
header('Refresh: 5; URL=https://example.com');
// Output a message to the user
echo "This is an example of using headers in PHP.";
?>
The following code will redirect your user to some another page.
1. <?php
2. // This will redirect the user to the new location
3. header('Location: http://www.javatpoint.com/');
4. //The below code will not execute after header
5. exit;
6. ?>
Output
It will redirect to the new URL location, which is given in header() function of the
above program, i.e., www.javatpoint.com. If any line of code is written after the
header(), it will not execute.
Example 2: Redirection interval
The following code will redirect to another page after 10 seconds.
1. <?php
2. // This will redirect after 10 seconds
3. header('Refresh: 10; url = http://www.javatpoint.com/');
4. exit;
5. ?>
Output
The output will be same as the example 1, but it will take 10 seconds to load.
Note: If any line of code is written after the header() function, it will not execute.
<?php
// Set the cache control headers to prevent caching
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Expires: Thu, 01 Jan 1970 00:00:00 GMT");
header("Pragma: no-cache");
?>
In the example above, the following cache control headers are set:
By using the following code,we can prevent the browser to cache pages.
1. <?php
2. // PHP program to describe header function
3.
4. // Set a past date
5. header("Expires: Tue, 03 March 2001 04:50:34 GMT");
6. header("Cache-Control: no-cache");
7. header("Pragma: no-cache");
8. ?>
9. <html>
10. <body>
11. <p>Hello Javatpoint!</p>
12.
13. <!-- PHP program to display
14. header list -->
15. <?php
16. print_r(headers_list());
17. ?>
18. </body>
19.</html>
Output
Hello Javatpoint!
Array (
[0] => X-Powered-By: PHP/7.3.13
[1] => Expires: Tue, 03 March 2001 04:50:34 GMT
[2] => Cache-Control: no-cache
[3] => Pragma: no-cache
)
Example 4
Create two php files, one of which for containing header file code and another for
redirecting to a new page on the browser.
headercheck.php
1. <?php
2. $host = $_SERVER['HTTP_HOST'];
3. $uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
4. $newpage = 'welcome.php';
5.
6. /* Redirect to a different page requested in the current directory*/
7. header("Location: http://$host$uri/$newpage");
8. exit;
9. ?>
welcome.php
Output
Other than HTML, you can also generate different types of data, e.g., you can
parse an image, zip, XML, JSON, etc.
Copy Code<?php
//Browser will deal page as PDF
header ( "Content-type: application/pdf" );
In this example, we show you how to specify a file for a user to download.
We first indicate the content type, which is a PDF file. You can specify other
content types such as images, audio, text, video, and other applications.
Secondly, we use a Content-Disposition header to indicate the file should be
downloaded rather than displayed in the web browser. Finally, in the same
header, we specify the filename, which will be the name of the file once it has
been downloaded.
Lastly, we use the readfile function to read a file and output it to the buffer. The
parameter of this function should be the location and name of the file you
would like available for download.
<?php
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="downloadName.pdf"');
readfile('localName.pdf');
?>
include() function:
This function is used to copy all the contents of a file, text wise into a file from
which it is called. This happens before the server executes the code.
Syntax
include ('filename');
Example
even.php
<?php
// File to be included
echo "Hello GeeksforGeeks";
?>
Now, include this file into another PHP file index.php
index.php
<?php
include("even.php");
echo "<br>Above File is Included"
?>
Output:
Example
Assume we have a file called "vars.php", with some variables defined:
<?php
$color='red';
$car='BMW';
?>
Then, if we include the "vars.php" file, the variables can be used in the calling
file:
<html>
<body>
<h1>Welcome to my home page!</h1>
<?php include 'vars.php';
echo "I have a $color $car.";
?>
</body>
</html>
Output:
even.php
<?php
// File to be included
echo "Hello GeeksforGeeks";
?>
Now, include this file using require()to index.php file. We will see the
contents of both files
index.php
<?php
require("even.php");
echo "<br>Above File is Required"
?>
Output:
include will only produce a warning (E_WARNING) and the script will
continue
require will produce a fatal error (E_COMPILE_ERROR) and stop the
script
Both functions act as same and produce the same results, but if by any
chance a fatal error arises, then the difference comes to the surface, which
we will see following this example. Consider the following code:
index.php
<?php
include("even.php");
echo "<br>Above File is Included"
?>
Output:
Now, if we don’t have a file named even.php, then in the case of the
include(), the following output will be shown with warnings about a missing
file, but at least the output will be shown from the index.php file:
In the case of the require(), if the file PHP file is missing, a fatal error will rise and no output is
shown and the execution halts.
This is the only difference. This also shows that require() function is better
than the include() function since the script should not continue executing if
files are missing or such an error is generated.
phpinfo() function
Syntax:
// Display detailed information about the PHP environment
phpinfo( );
Example:
<?php phpinfo(); ?>
You will get the information displayed like in the image given below:
Other than all the information ,if you want specific information about variables
only or license only, you can do that .You just have to pass an argument in the
function either as name or their specific value. Every information has given a
particular keyword and a value associated with it which we can use in
the phpinfo() function to get only selective information. Look at the table given
below:
Valu
Name (constant) e Description
INFO_MODULES 8 Shows information about all the Loaded modules and their s
Recursive Function
Recursion is a programming technique where a function calls itself. Recursive
functions have two parts. “Base case”(terminating condition) and the
“Recursive case”.
Make sure that the recursive function has a base case. The base case is the
condition that terminates the recursion. Without a base case, the recursion will
continue forever and eventually lead to a stack overflow.
It is recommended to avoid recursive function call over200 recursion level
because it may smash the stack and may cause the termination of script.
Recursion is a good choice for problems that can be broken down into smaller
sub problems of the same type. For example, recursion is well-suited for solving
problems such as traversing a tree or graph, searching for an element in a list,
generating permutations or combinations of elements and sorting a list.
However, it is important to note that recursion can also lead to stack overflows
if not used correctly. Therefore, it is important to use recursion carefully and to
be aware of the potential pitfalls.
// Base case
// Recursive function
<?php
function fact($n)
// Base case
if ( $n === 0 ) {
return 1;
// recursive function
echo fact(4); // 4 * 3 * 2 * 1 = 24
?>
Output:
24
When called fact(4) it went into the function and got fact(3) and then it
went into fact(3) and got fact(2)… .. and so on. Finally, it went
to fact(0) and got 1 from the base case.
<?php
function display($number)
if($number<=5){
display($number+1); }
display(1);
?>
Output:
1
2
3
4
5
Strings
PHP string is a sequence of characters i.e., used to store and manipulate text.
Example:
<?php
echo "Hello";
print "Hello";
?>
HelloHello
E.g. when there is a variable in the string, it returns the value of the
variable:
Example
Double quoted string literals perform operations for special
characters:
<?php
$x = "John";
?>
Output
Hello John
Single quoted string does not perform such tions; it returns the string like it
was written, with the variable name:
Example
Single quoted string literals returns the string as it is:
<?php
$x = "John";
?>
Output
Hello $x
String Functions
The PHP string functions are part of the PHP core. No installation is required to
use these functions.
Length of a string
// output: 17
echo strlen($str);
?>
The empty() function returns true if a string variable is “empty.” Empty string
variables are those with the values ' ', 0, '0', or NULL. The empty() function also
returns true when used with a non-existent variable.
<?php
// output: true
// output: true
$str = null;
// output: true
$str = '0';
// output: true
unset($str);
echo (boolean)empty($str);
?>
<?php
// reverse string
echo strrev($str);
?>
To repeat a string, PHP offers the str_repeat() function, which accepts two
arguments—the string to be repeated, and the number of times to repeat it.
<?php
// repeat string
// output: 'yoyoyo'
$str = 'yo';
?>
PHP also allows you to slice a string into smaller parts with the substr()
function,which accepts three arguments: the original string, the position
(offset) at which to start slicing, and the number of characters to return from
the starting position. The following listing illustrates this in action:
<?php
// extract substring
// output: 'come'
?>
When using the substr() function, the first character of the string is treated as
offset 0, the second character as offset 1, and so on.
To extract a substring from the end of a string (rather than the beginning), pass
substr() a negative offset.
<?php
// extract substring
?>
If you need to compare two strings, the strcmp() function performs a case-
sensitive comparison of two strings, returning a negative value if the first is
“less” than the second, a positive value if it’s the other way around, and zero if
both strings are “equal.” Here are some examples of how this works:
<?php
// compare strings
$a = "hello";
$b = "hello";
$c = "hEllo";
// output: 0
// output: 1
?>
<?php
// count words
// output: 5
echo str_word_count($str);
?>
If you need to perform substitution within a string, PHP also has the
str_replace() function, designed specifically to perform find-and-replace
operations. This function accepts three arguments: the search term, the
replacement term, and the string in which to perform the replacement. Here’s
an example:
<?php
$str = 'john@domain.net';
Formatting Strings
<?php
echo trim($str);
?>
<?php
echo strtolower($str);
echo strtoupper($str);
?>
You can also uppercase the first character of a string with the ucfirst()
function, or format a string in “word case” with the ucwords() function. The
following listing demonstrates both these functions:
<?php
echo ucwords($str);
echo ucfirst($str);
?>
String Concatenation
To concatenate, or combine, two strings you can use the . (dot) operator.
<?php
$x = "Hello";
$y = "World";
$z = $x . $y;
echo $z;
?>
HelloWorld
Copy String
<?php
$copiedStr = $str;
echo $copiedStr;
?>
Output
Hello, World!
The strval() function can be used to convert a variable to a string. This function
can also be used to copy a string. This approach is particularly useful when the
original variable is not strictly a string (e.g., a number or an object) but needs
to be copied as a string.
<?php
// strval() function
$copiedStr = strval($str);
echo $copiedStr;
?>
Output
Hello, World!
The substr() function can be used to extract a substring from a string. In this
case, we’re starting from the beginning (offset 0) and extracting the entire
string, effectively creating a copy.
<?php
// substr() function
echo $copiedStr;
?>
Output
Hello, World!
<?php
// strcpy() function
$destination = $source;
strcpy($copiedStr, $str);
echo $copiedStr;
?>
Output
Hello, World!