0% found this document useful (0 votes)
28 views45 pages

UNIT III - Functions in PHP

Notes

Uploaded by

zerobgmi00
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
28 views45 pages

UNIT III - Functions in PHP

Notes

Uploaded by

zerobgmi00
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 45

Functions

A function is a block of code written in a program to perform some specific


tasks.

PHP provides two major types of functions:

 Built-in functions: PHP provides us with huge collection of built-in library


functions. These functions are already coded and stored in form of
functions. To use those we just need to call them as per our
requirement like, var_dump, fopen(), print(), gettype() and so on.. ...
 User Defined Functions: Apart from the built-in functions, PHP allows us
to create our own customised functions called the user-defined
functions. Using this we can create our own packages of code and use it
wherever necessary by simply calling it.

Advantage of PHP Functions

1) Code reusability: PHP functions are defined only once and can be invoked
many times, like in other programming languages.

2) Efficiency in code: PHP streamlines code development by reducing the need


for redundant logic. Rather than having to rewrite the same logic repeatedly,
we can create functions once and employ them as needed, resulting in concise
and efficient code.
3) Enhanced readability: PHP's division of programming logic into functions
enhances the clarity of application flow. By isolating each piece of logic within
its function, it becomes more straightforward to understand the overall
structure of the application.

4) Time savings: Reusing code through functions saves a substantial amount of


time during the development process. Developers can focus on creating new
functionality rather than reinventing the old one.

5) Scalability: As your project grows, the ability to reuse code becomes


increasingly valuable. Functions can be expanded and modified as needed,
allowing the codebase to scale without becoming very complex.

6) Easier error detection: Testing individual functions is more straightforward


than testing an entire application. Since, our code is divided into functions, we
can easily detect in which function, the error could lie and fix them fast and
easily.

7) Easy maintenance: As we have used functions in our program, so if


anything, or any line of code needs to be changed, we can easily change it
inside the function and the change will be reflected everywhere, where the
function is called. Hence, easy to maintain.

Creating a Function

While creating a user defined function we need to keep few things in mind:

1. Any name ending with an open and closed parenthesis is a function.


2. A function name always begins with the keyword function.
3. To call a function we just need to write its name followed by the
parenthesis
4. A function name cannot start with a number. It can start with an
alphabet or underscore.
5. A function name is not case-sensitive.

Syntax:

function function_name(){
executable code;
}

A user-defined function declaration starts with the keyword function, followed


by the name of the function.

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() {

echo "Hello world!";

To call the function, just write its name followed by parentheses ():

function myMessage() {

echo "Hello world!";

myMessage();

Example

<?php
function sayHello(){
echo "Hello PHP Function";
}
sayHello(); //calling function
?>

Output:

Hello PHP Function


Normally, there are three components to every function:
● Arguments, which serve as inputs to the function
● Return values, which are the outputs returned by the function
● The function body, which contains the processing code to turn inputs into
outputs

Function: Returning Value

Example of function that returns value.

<?php
function cube($n){
return $n*$n*$n;
}
echo "Cube of 3 is: ".cube(3);
?>

Output:

Cube of 3 is: 27

Function Parameters or Arguments

The information or variable, within the function’s parenthesis, are called


parameters. We can pass the information through arguments which is
separated by comma.
Parameter passing to Functions
PHP allows the following ways in which an argument can be passed into a
function:

 Call by Value (default) or Pass by Value

 Call by Reference or Pass by Reference

 Default argument values


 Variable-length argument list or dynamic argument list

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.

Example to pass single argument


<?php
function sayHello($name){
echo "Hello $name<br/>";
}
sayHello("Sonoo");
sayHello("Vimal");
sayHello("John");
?>

Output:

Hello Sonoo
Hello Vimal
Hello John

Example to pass two arguments

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

On passing arguments as pass by reference, the original value is passed.


Therefore, the original value gets altered. In pass by reference, we actually
pass the address of the value. To pass value as a reference, we need to use
ampersand (&) symbol before the argument name.

Example of call by reference

<?php
function adder(&$str2)
{
$str2 .= 'Call By Reference';
}
$str = 'Hello ';
adder($str);
echo $str;
?>
Output:
Hello Call By Reference

Default Argument Value

We can specify a default argument value in function. While calling PHP


function if you don't specify any argument, it will take the default argument.

Example for default argument list


<?php
function sayHello($name="Sonoo"){
echo "Hello $name<br>";
}
sayHello("Rajesh");
sayHello(); //passing no value
sayHello("John");
?>

Output:

Hello Rajesh
Hello Sonoo
Hello John

Variable-length argument list

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

for($i = 0; $i < $len; $i++) {

$n += $x[$i];

}
return $n;

$a = sumMyNumbers(5, 2, 6, 2, 7, 7);

echo $a;

?>

Output:

29

Example A function that accepts an arbitrary number of arguments, adds them


up, and returns the average

<?php

// calculate average of supplied values

function calcAverage() {

$args = func_get_args();

$count = func_num_args();

$sum = array_sum($args);

$avg = $sum / $count;

return $avg;

// function invocation with 3 arguments // output: 6

echo calcAverage(3,6,9);

// function invocation with 8 arguments // output: 150

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.

The func_num_ args() function returns the number of arguments passed to a


function, while the func_ get_args() function returns the actual argument
values, as an array.

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:

 echo has no return value while print has a return value of 1 so


it can be used in expressions.
 echo can take multiple parameters (although such usage is
rare) while print can take one argument.
 echo is marginally faster than print.

The PHP echo Statement


Display Text
<html>
<body>
<?php
echo "<h2>PHP is Fun!</h2>";
echo "Hello world!<br>";
echo "I'm about to learn PHP!";
?>
</body>
</html>
Output
PHP is Fun!
Hello world!
I'm about to learn PHP!

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

Example (Check multiple arguments)


You can pass multiple arguments separated by a comma (,) in echo. It
will not generate any syntax error.

<?php
$fname = "Gunjan";
$lname = " Gunjan ";
echo "My name is: ".$fname,$lname;
?>

Output:

It will generate a syntax error because of multiple arguments in a


print statement.

<?php
$fname = "Gunjan";
$lname = "Garg";
print "My name is: ".$fname,$lname;
?>

Output:

Example (Check Return Value)

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:

As we already discussed that print returns a value, which is always 1.

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

Uses of header() function


 It changes the page location and redirects the page.
 It sets content type and prompts to download content.
 It prepares the HTTP status code to respond with.
 It sets caching properties and overrides existing caching behaviour.
 It sets the time zone.
 It sends the STOP status.

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:

 $header (required): Specifies the header to be sent. It should be a valid


HTTP header string, such as "Content-Type: text/html" or
"Location: https://example.com".
 $replace (optional): Indicates whether the specified header should
replace a previous header with the same name. By default, it is set to
true, allowing replacement of the header. If set to false, the new header
will be appended to any existing headers with the same name.
 $http_response_code (optional): Specifies the HTTP response code to be
sent. It can be used to send specific HTTP status codes such as 200, 404,
or 500. If not provided, the server will use the default response code of
200 (OK).
 The PHP header() function does not return any value.

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:

 Example: header('Content-Type: text/html')

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

 Example: header('Location: https://example.com')

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')

Controls caching behavior in the browser. Values like no-cache, no-store,


private, public, etc., can be used to specify cache control directives.

Expires:

 Example: header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 3600) . ' GMT')

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:

 Example: header('Content-Disposition: attachment; filename="file.pdf"')

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:

 Example: header('HTTP/1.1 404 Not Found')

Sets the HTTP response code for the current request. Common codes include
200 OK, 404 Not Found, 500 Internal Server Error, etc.

Basic Working Example

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

In the above example


 The header('Content-Type: text/plain') line sets the Content-Type header to
specify that the response should be treated as plain text. This is useful when
you want to send text-based content to the browser.
 The header('X-Custom-Header: Hello, world!') line sets a custom header
named X-Custom-Header with the value "Hello, world!". This demonstrates
how you can add custom headers to your PHP responses.

 The header('Refresh: 5; URL=https://example.com') line sends a Refresh


header that redirects the user to the specified URL (https://example.com)
after 5 seconds. This is useful for performing redirects or refreshing a page
after a certain time.

Example 1: Redirecting browser

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.

Example 3: Don't cache pages

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

 Cache-Control: no-store - Specifies that the response should not be stored in


any cache, including the browser cache or intermediate caches.
 Cache-Control: no-cache - Indicates that the response can be cached, but it
must be revalidated with the server on each request. The cached copy cannot
be used without first checking with the server.
 Cache-Control: must-revalidate - Instructs the browser and intermediate
caches to revalidate the response with the server before using a cached copy.
 Cache-Control: max-age=0 - Sets the maximum age of the response to 0
seconds, effectively telling the browser to always revalidate the response with
the server. Run the above code in your editor for a better and clear
explanation.
 Second header specifies a expires header set to a date in the past. Having a
past date means the response is always considered stale and thus is unlikely
to be cached.
 Pragma: no-cache to make sure it gets a fresh server copy each time.

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

1. <!-- welcome.php file redirect to new page -->


2. <html>
3. <head>
4. <title> Welcome page </title>
5. </head>
6. <body>
7. <h1> <center> Welcome to javaTpoint </center> </h1>
8. </body>
9. </html>

Output

Example 5: Content Types

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

//myPDF.pdf will called


header ( "Content-Disposition: attachment; filename=myPDF.pdf' " );
?>

Example 6: Download Files

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

Example 7: Set HTTP Status in the header response.

header("HTTP/1.0 404 Not Found");


include and require functions
We can insert the content of one PHP file into another PHP file (on the server
side) before server executes it.
There are two functions that help us to include files:
 include()
 require()
Scripting the same function in multiple pages is a task of great effort and would
consume lots of time & also impact the execution of the code. This can be
avoided if we follow and use the concept of file inclusion which helps us to
include various files including text or codes into a single program which saves
the effort of writing the full function or code multiple times. This also provides
another advantage. If we want to change any code then instead of editing it in
all the files, we just need to edit the source file and all codes will be
automatically changed. This concept allows us to re-use content throughout
your website.
For example, you could have a standard header and footer on every page of
your website. Instead of copying/pasting this code on to every page, you could
simply place your header code into one include file and your footer code into
another include file. Then, on every page, all you need to do is refer to the
header and footer include files. You can do this either using the include()
function or the require() function.

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:

Welcome to my home page!


I have a red BMW.
require() function:
The require() function performs same as the include() function. It also takes the
file that is required and copies the whole code into the file from where the
require() function is called.
Syntax
require ('filename');
Example

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:

Difference between include() function and require() function :


The include and require statements are identical, except upon failure(the way
they handle errors):

 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

The phpinfo() is a very important function which gives us information about


the PHP configuration and installation in our system. Every system is different
and hence this information would be different for each of them as well. It can
also be used to identify installation and configuration problems. Whenever the
phpinfo() function is called without any argument then it will display all the
information about the PHP configuration in the system, some of the
information includes:

 PHP compilation options and extensions information


 PHP version
 Server information (if compiled as a module)
 PHP environment
 HTTP headers

phpinfo() is primarily used for development and debugging purposes


and should not be enabled on production servers for security reasons.

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_GENERAL 1 Information about platform, php.ini location, web system, e

INFO_CREDITS 2 Return all the information about the authors, documentati


credits.

INFO_CONFIGURATION 4 Returns PHP core configuration information.


Valu
Name (constant) e Description

INFO_MODULES 8 Shows information about all the Loaded modules and their s

INFO_ENVIRONMENT 16 Returns all Environment Variable information.

INFO_VARIABLES 32 Shows all predefined variables like GET, POST, etc.

INFO_LICENSE 64 Shows information about PHP license

INFO_ALL -1 Shows all the information.

Note: php_info(INFO_MODULES) and php_info(8) and also all other constants


and their respective values give the same result, i.e. they can be used
interchangeably.
Note: php_info() and php_info(INFO_ALL) gives the same output.

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.

When to use recursion

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.

Skeleton of a Recursive function:


function name()

// Base case

// Recursive function

Example : Factorial of a number

<?php
function fact($n)

// Base case

if ( $n === 0 ) {
return 1;

// recursive function

return ($n * fact( $n - 1 ));

echo fact(4); // 4 * 3 * 2 * 1 = 24

?>

Output:
24

The diagram below shows the entire process of recursion.

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.

Then it started returning the value to fact(1), fact(2)… .. and so on,


that’s why finally fact(4) got 6 from fact(3).
Example 2: Printing number

<?php

function display($number)

if($number<=5){

echo "$number <br>";

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.

Strings in PHP are surrounded by either double quotation marks, or single


quotation marks.

Example:

<?php
echo "Hello";

print "Hello";

?>

HelloHello

Double or Single Quotes?


You can use double or single quotes, but you should be aware of the
differences between the two.

Double quoted strings perform action on special characters.

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

echo "Hello $x";

?>

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

echo 'Hello $x';

?>

Output

Hello $x

String Functions
The PHP string functions are part of the PHP core. No installation is required to
use these functions.

PHP has over 75 built-in string manipulation functions, supporting operations


ranging from string repetition and reversal to comparison and search-and-
replace. Some of these functions are,

Function What It Does

empty() Tests if a string is empty

strlen() Calculates the number of characters in a string

strrev() Reverses a string

str_repeat() Repeats a string

substr() Retrieves a section of a string

strcmp() Compares two strings


str_word_count() Calculates the number of words in a string

str_replace() Replaces parts of a string

trim() Removes leading and trailing whitespace


from a string

strtolower() Lowercases a string

strtoupper() Uppercases a string

ucfirst() Uppercases the first character of a string

ucwords() Uppercases the first character of every


word of a string

addslashes() Escapes special characters in a string with


backslashes

stripslashes() Removes backslashes from a string

htmlentities() Encodes HTML within a string

htmlspecialchars() Encodes special HTML characters within a


string

nl2br() Replaces line breaks in a string with <br/>


elements

strip_tags() Removes PHP and HTML code from a string

html_entity_decode() Decodes HTML entities within a string

htmlspecialchars_decode() Decodes special HTML characters


within a string

Common PHP String Functions

Length of a string

The strlen() function returns the number of characters in a string.


<?php

// calculate length of string

// output: 17

$str = 'Welcome to Xanadu';

echo strlen($str);

?>

Checking for Empty Strings

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

// test if string is empty

// output: true

$str = ' ';

echo (boolean) empty($str);

// output: true

$str = null;

echo (boolean) empty($str);

// output: true

$str = '0';

echo (boolean) empty($str);

// output: true
unset($str);

echo (boolean)empty($str);

?>

Reversing and Repeating Strings

Reversing a string is as simple as calling the strrev() function, as in the next


listing:

<?php

// reverse string

// output: 'pets llams enO'

$str = 'One small step';

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

echo str_repeat($str, 3);

?>

Working with Substrings

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'

$str = 'Welcome to nowhere';

echo substr($str, 3, 4);

?>

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

// output: 'come here'

$str = 'Welcome to nowhere';

echo substr($str, 3, 5) . substr($str, -4, 4);

?>

Comparing, Counting, and Replacing Strings

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

echo strcmp($a, $b);

// output: 1

echo strcmp($a, $c);

?>

PHP’s str_word_count() function provides an easy way to count the number


of words in a string.

<?php

// count words

// output: 5

$str = "The name's Bond, James Bond";

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

// replace '@' with 'at'

// output: 'john at domain.net'

$str = 'john@domain.net';

echo str_replace('@', ' at ', $str);


?>

Formatting Strings

PHP’s trim() function can be used to remove leading or trailing whitespace


from a string; this is quite useful when processing data entered into a Web
form.

<?php

// remove leading and trailing whitespace

// output 'a b c'

$str = ' a b c ';

echo trim($str);

?>

Changing the case of a string

It is as simple as calling the strtolower() or strtoupper() function, as illustrated


in the next listing:

<?php

// change string case

$str = 'Yabba Dabba Doo';

// output: 'yabba dabba doo'

echo strtolower($str);

// output: 'YABBA DABBA DOO'

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

// change string case

$str = 'the yellow brigands';

// output: 'The Yellow Brigands'

echo ucwords($str);

// output: 'The yellow brigands'

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

 Copy String using Assignment Operator


 Copy String using strval() Function
 Copy String using substr() Function
 Implementing a strcpy() Function

Copy String using Assignment Operator


The simplest way to copy a string in PHP is by using the assignment operator
(=). This operator copies the value from the right-hand side to the left-hand
side.

Example: Illustration of copying a string in PHP using the assignment operator.

<?php

$str = "Hello, World!";

// copying a string using assignment operator

$copiedStr = $str;

echo $copiedStr;

?>

Output

Hello, World!

Copy String using strval() Function

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.

Example: Illustration of copying a string in PHP using the strval() function.

<?php

$str = "Hello, World!";

// copying a string using

// strval() function

$copiedStr = strval($str);
echo $copiedStr;

?>

Output

Hello, World!

Copy String using substr() Function

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.

Example: Illustration of copying a string in PHP using the substr() function.

<?php

$str = "Hello, World!";

// copying a string using

// substr() function

$copiedStr = substr($str, 0);

echo $copiedStr;

?>

Output

Hello, World!

Implementing a strcpy() Function


While PHP does not have a native strcpy() function like C, you can implement a
similar function using string assignment. This custom strcpy() function takes
two parameters: a reference to the destination string and the source string.

Example: Illustration of copying a string in PHP by implementing a strcpy()


function.

<?php

// strcpy() function

function strcpy(&$destination, $source)

$destination = $source;

$str = "Hello, World!";

strcpy($copiedStr, $str);

echo $copiedStr;

?>

Output

Hello, World!

You might also like