0% found this document useful (0 votes)
36 views31 pages

Unit III PHP

This document provides an overview of PHP functions, including built-in and user-defined functions, their syntax, and how to create and call them. It explains function parameters, return values, variable scope, and the concept of default parameters. Additionally, it covers advanced topics such as variable arguments, returning multiple values, and variable functions.
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)
36 views31 pages

Unit III PHP

This document provides an overview of PHP functions, including built-in and user-defined functions, their syntax, and how to create and call them. It explains function parameters, return values, variable scope, and the concept of default parameters. Additionally, it covers advanced topics such as variable arguments, returning multiple values, and variable functions.
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/ 31

UNIT III

PHP Functions
A PHP function is a block of code that performs a specific task and can be called multiple
times within a PHP script. Functions are a key building block for developing and maintaining
applications in PHP
PHP provides us with 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_r(), 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.
User-defined Functions:
 User-defined functions are created by the programmer to perform specific tasks
according to their requirements.
 These functions are declared using the function keyword followed by a function name
and a block of code encapsulated within curly braces {}.
 They can accept parameters (input data) and return values (output data) using
the return statement.
 User-defined functions provide a way to encapsulate reusable code, promote
modularity, and enhance code readability and maintainability.
Syntax:
function greet($name) {
return "Hello, $name!";
}
Example
<?php
function sayHello(){
echo "Hello PHP Function";
}
sayHello();//calling function
?>
Output:
Hello PHP Function
Built-in Functions:
 Built-in functions, also called predefined or library functions, are included in PHP by
default.
 They perform common tasks like handling strings, arrays, files, math operations, and
databases.
 These functions save time and effort as they are already implemented and available for use.
 PHP offers a vast range of built-in functions, providing developers with tools to complete
tasks quickly and efficiently.
Syntax:
$string = "Hello, world!";
$length = strlen($string);

// Built-in function to find the length of a string


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;
}
Example:
<?php

function funcGeek()
{
echo "This is Students";
}

// Calling the function


funcGeek();

?>
Output:
This is Students

Function Parameters or Arguments


The information or variable, within the function’s parenthesis, are called
parameters. These are used to hold the values executable during runtime. A user is free
to take in as many parameters as he wants, separated with a comma(,) operator. These
parameters are used to accept inputs during runtime. While passing the values like
during a function call, they are called arguments. An argument is a value passed to a
function and a parameter is used to hold those arguments. In common term, both
parameter and argument mean the same. We need to keep in mind that for every
parameter, we need to pass its corresponding argument.
Syntax:

function function_name($first_parameter, $second_parameter) {


executable code;
}

Example:
<?php

// function along with three parameters


function proGeek($num1, $num2, $num3)
{
$product = $num1 * $num2 * $num3;
echo "The product is $product";
}

// Calling the function


// Passing three arguments
proGeek(2, 3, 5);

?>
Output:
The product is 30
Setting Default Values for Function parameter
PHP allows us to set default argument values for function parameters. If we
do not pass any argument for a parameter with default value then PHP will use the
default set value for this parameter in the function call.
Example:
<?php

// function with default parameter


function defGeek($str, $num=12)
{
echo "$str is $num years old \n";
}

// Calling the function


defGeek("Ram", 15);

// In this call, the default value 12


// will be considered
defGeek("Adam");

?>
Output:
Ram is 15 years old
Adam is 12 years old
Returning Values from Functions
Functions can also return values to the part of program from where it is
called. The return keyword is used to return value back to the part of program, from
where it was called. The returning value may be of any type including the arrays and
objects. The return statement also marks the end of the function and stops the
execution after that and returns the value.
Example:
<?php

// function along with three parameters


function proGeek($num1, $num2, $num3)
{
$product = $num1 * $num2 * $num3;

return $product; //returning the product


}

// storing the returned value


$retValue = proGeek(2, 3, 5);
echo "The product is $retValue";

?>
Output:
The product is 30
Parameter passing to Functions
PHP allows us two ways in which an argument can be passed into a function:
 Pass 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.
 Pass by Reference: 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, where it is stored using ampersand
sign(&).

Example:
<?php
// pass by value
function valGeek($num) {
$num += 2;
return $num;
}
// pass by reference
function refGeek(&$num) {
$num += 10;
return $num;
}
$n = 10;
valGeek($n);
echo "The original value is still $n \n";
refGeek($n);
echo "The original value changes to $n";

?>
Output:
The original value is still 10
The original value changes to 20

Declare and Call a Function in PHP


Declaring and calling functions in PHP involves defining the function using
the function keyword, specifying any parameters it may accept, and then invoking the function
when needed within the script.
Steps:
 Function Declaration: Use the function keyword followed by the function name and a
block of code enclosed within curly braces {} to define a function.
 Function Parameters: Define any parameters the function may accept within the
parentheses ().
 Function Body: Write the code that the function will execute within the curly
braces {}.
 Function Call: Invoke the function by its name followed by parentheses () containing
any required arguments.
Syntax:
// Function declaration
function functionName($param1, $param2, ...)
{
// Function body
// Perform specific tasks here
}
// Function call
functionName($arg1, $arg2, ...);

Example: Illustration of declaration and calling a function in PHP


<?php
// Function declaration
function greet($name) {
echo "Hello, $name!";
}
// Function call
greet("John");
?>
Output
Hello, John!
Difference between Function Declaration and Function Call

Function Declaration Function Call

Defines the structure and behavior of a Invokes the function to execute its defined
function behavior

Begins with the function keyword Consists of the function name followed by
followed by the function name and parentheses containing any required
parameters (optional) arguments

Contains the code to be executed when Triggers the execution of the function's
the function is called code block with specified input values

PHP Variable Scope


The scope of a variable is defined as its range in the program under which it can be accessed.
In other words, "The scope of a variable is the portion of the program within which it is defined and
can be accessed."
PHP has three types of variable scopes:
1. Local variable
2. Global variable
3. Static variable

Local variable
The variables that are declared within a function are called local variables for that function.
These local variables have their scope only in that particular function in which they are declared.
This means that these variables cannot be accessed outside the function, as they have local scope.
A variable declaration outside the function with the same name is completely different from the
variable declared inside the function.
Example:
<?php
function local_var()
{
$num = 45; //local variable
echo "Local variable declared inside the function is: ". $num;
}
local_var();
?>
Output:
Local variable declared inside the function is: 45

Global variable
The global variables are the variables that are declared outside the function. These variables
can be accessed anywhere in the program. To access the global variable within a function, use the
GLOBAL keyword before the variable. However, these variables can be directly accessed or used
outside the function without any keyword. Therefore there is no need to use any keyword to access a
global variable outside the function.
Example:
<?php
$name = "Sanaya Sharma"; //Global Variable
function global_var()
{
global $name;
echo "Variable inside the function: ". $name;
echo "</br>";
}
global_var();
echo "Variable outside the function: ". $name;
?>
Output:
Variable inside the function: Sanaya Sharma
Variable outside the function: Sanaya Sharma

Static variable
It is a feature of PHP to delete the variable, once it completes its execution and memory is
freed. Sometimes we need to store a variable even after completion of function execution. Therefore,
another important feature of variable scoping is static variable. We use the static keyword before the
variable to define a variable, and this variable is called as static variable.
Static variables exist only in a local function, but it does not free its memory after the
program execution leaves the scope. Understand it with the help of an example:
Example:
<?php
function static_var()
{
static $num1 = 3; //static variable
$num2 = 6; //Non-static variable
//increment in non-static variable
$num1++;
//increment in static variable
$num2++;
echo "Static: " .$num1 ."</br>";
echo "Non-static: " .$num2 ."</br>";
}

//first function call


static_var();

//second function call


static_var();
?>
Output:
Static: 4
Non-static: 7
Static: 5
Non-static: 7

Default Parameters
The default parameter concept comes from C++ style default argument values,
same as in PHP you can provide default parameters so that when a parameter is not
passed to the function. Then it is still available within the function with a pre-defined
value. This function also can be called optional parameter.
Syntax:
function greeting($name=" parameter_value ")
Parameter: This function accepts a single parameter that is $name here, holds the
parameter value.
Below examples illustrate the procedure to create and use the default function
parameter.
Example 1:
<?php
function greeting($name=" Students ")
{
echo "Welcome to $name ";
echo("\n");
}
greeting("Gfg");

// Passing no value
greeting();
greeting("A Computer Science Portal");
?>
Output:
Welcome to Gfg
Welcome to Students
Welcome to A Computer Science Portal

Variable Parameters
We will take up each word one by one to deeply understand the topic we are dealing
with.
 Variable: It is the number of arguments keeps changing.
 Length: It refers to the number of arguments.
 Argument: It refers input passed to a function.
Now, the point of interest lies at the word list, all the arguments passed at its call will go
the function as an array. The values will be retrieved like they are being from an array.
Accessing Variable Arguments Method: In this, the function is made to accept variable
arguments and work accordingly. The variable which has to have multiple numbers of
arguments is declared with “…”(triple dots).
<?php
function sum(...$numbers) {
$res = 0;
foreach($numbers as $n) {
$res+=$n;
}
return $res;
}

echo(sum(1,2,3,4)."\n");
echo(sum(5,6,1));
?>
Output:
10
12

Providing Variable Arguments Method: You can also use “…”(triple dots) when calling
functions to unpack an array or Traversable variable or literal into the argument list.
Example:
<?php
function add($a,$b) {
return $a + $b ;
}
echo add(...[1, 2])."\n";

$a = [1, 2];
echo add(...$a);
?>
Output:
3
3
MISSING PARAMETERS
When you call a function, you can pass any number of arguments to the function.
Any parameters the function expects that are not passed to it remain unset, and a warning
is issued for each of them:

Returning values
Values are returned by using the optional return statement. Any type may be returned,
including arrays and objects. This causes the function to end its execution immediately and pass
control back to the line from which it was called. See return for more information.
If the return is omitted the value null will be returned.
Use of return
Example1 Use of return
<?php
function square($num)
{
return $num * $num;
}
echo square(4); // outputs '16'.
?>

Returning Multiple Values using an Array


Most common and basic method to return multiple values from a function in PHP is
by returning an array. This approach allows you to bundle multiple values together and
return them as a single entity.
Example 1: This example returns multiple values from a function using array
<?php

function getUserInfo() {
$name = "XYZ";
$age = 20;
$email = "[email protected]";

// Return multiple values as an array


return [$name, $age, $email];
}

// Retrieve the Returned Array


$userInfo = getUserInfo();

// Destructure array into variables


list($name, $age, $email) = $userInfo;

echo "Name: $name, Age: $age, Email: $email";

?>
Output
Name: XYZ, Age: 20, Email: [email protected]
Returning Multiple Values using an Object
Another approach to return multiple values is to return an object. This is
particularly useful when you want to return structured data or when you prefer object-
oriented programming practices.
<?php
class User {
public $name;
public $age;
public $email;

public function __construct($name, $age, $email) {


$this->name = $name;
$this->age = $age;
$this->email = $email;
}
}

function getUserInfo() {
// Return an object with multiple values
return new User("XYZ", 20, "[email protected]");
}
// Retrieve the Returned Object
$user = getUserInfo();
echo "Name: $user->name, Age: $user->age, Email: $user->email";

?>

Output
Name: XYZ, Age: 20, Email: [email protected]
Variable Functions
If name of a variable has parentheses (with or without parameters in it) in front of it, PHP
parser tries to find a function whose name corresponds to value of the variable and executes it.
Such a function is called variable function. This feature is useful in implementing callbacks,
function tables etc.
Variable function example
In following example, value of a variable matches with function of name. The function is
thus called by putting parentheses in front of variable
<?php
function hello(){
echo "Hello World";
}
$var="Hello";
$var();
?>
Output
Hello World

Here is another example of variable function with arguments


Example
<?php
function add($x, $y){
echo $x+$y;
}
$var="add";
$var(10,20);
?>
Output
30
Variable method example
Concept of variable function can be extended to method in a class
Example
<?php
class myclass{
function welcome($name){
echo "Welcome $name";
}
}
$obj=new myclass();
$f="welcome";
$obj->$f("Amar");
?>
Output
Welcome Amar
Anonymous Function
Anonymous Function, also known as closures, are functions in PHP that do not have
a specific name and can be defined inline wherever they are needed. They are useful for
situations where a small, one-time function is required, such as callbacks for array functions,
event handling, or arguments to other functions.
Syntax:
$anonymousFunction = function($arg1, $arg2, ...) {
// Function body
};

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.
Example
Anonymous function example
<?php
$var = function ($x) {return pow($x,3);};
echo "cube of 3 = " . $var(3);
?>
Output
cube of 3 = 27
Anonymous function as 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.
In following example, an anonymous function is used as argument for a built-in usort()
function. The usort() function sorts a given array using a comparison function
Example
<?php
$arr = [10,3,70,21,54];
usort ($arr, function ($x , $y) { return $x > $y;
});
foreach ($arr as $x){ echo $x . "\n";
}
?>
Output
3
10
21
54
70
Introduction to Strings
PHP Strings
A string is a sequence of characters used to store and manipulate text data. PHP
strings can include letters, numbers, symbols, and special characters. Strings are a
versatile data type, commonly used for handling input/output, generating dynamic
content, and more.
Declaration of String in PHP
Strings in PHP can be declared using single quotes, double quotes, heredoc,
and nowdoc syntax.
1. Single Quotes
Single quotes are used to define simple strings in PHP. The text within single
quotes is treated literally, meaning special characters and variables are not interpreted.
PHP

<?php

// Singlequote strings
$site = 'Welcome to Students';

echo $site;

?>
Output
Welcome to Students

2. Double Quotes
Unlike single-quote strings, double-quote strings in PHP are capable of
processing special characters.
<?php

// Double Quote Strings


echo "Welcome to Students \n";

$site = " Students";

echo "Welcome to $site";

?>
Output
Welcome to Students
Welcome to Students
3. Heredoc Syntax
The syntax of Heredoc (<<<) is another way to delimit PHP strings. An
identifier is given after the heredoc (<<< ) operator, after which any text can be
written as a new line is started. To close the syntax, the same identifier is given
without any tab or space. Heredoc syntax is similar to the double-quoted string,
without the quotes.
<?php
$input = <<<testHeredoc
Welcome to Students.
Started content writing in Students!.
I am enjoying this.
testHeredoc;

echo $input;

?>
Output
Welcome to Students.
Started content writing in Students!.
I am enjoying this.

4. Nowdoc Syntax
Nowdoc is very much similar to the heredoc other than the parsing done in
heredoc. The syntax is similar to the heredoc syntax with symbol <<< followed by
an identifier enclosed in single-quote. The rule for nowdoc is the same as heredoc.
Nowdoc syntax is similar to the single-quoted string.
<?php
$input = <<<'testNowdoc'
Welcome to Students.
Started content writing in Students!.
testNowdoc;
echo $input;
// Directly printing string
// without any variable
echo <<<'Nowdoc'
Welcome to GFG .
Learning PHP is fun in GFG.
Nowdoc;
?>
Output
Welcome to Students.
Started content writing in Students!.
Welcome to GFG.
Learning PHP is fun in GFG.

Variable Interpolation
Variable interpolation is adding variables in between when specifying a string
literal. PHP will parse the interpolated variables and replace the variable with its value
while processing the string literal.
A string literal can be specified in four ways,
1. Single quoted
2. Double quoted
3. Heredoc syntax
4. Nowdoc syntax
 Interpolation: The variable parsing is allowed when the string literal is enclosed
with double quotes or with heredocs.
 Single quoted string or nowdocs, does not supports variable interpolation.
We are going to see examples for interpolating a variable in a heredoc and with a
string literal that is enclosed by double-quotes. This will show how it will be helpful
in PHP string concatenation.
Variable interpolation syntaxes
There are two syntaxes using which the variable interpolation can be done in PHP.
1. Simple syntax: Just put the variable within the string literal.
2. Complex syntax: Specify the variable within curly braces. The reason it is
called as ‘complex’ is that it allows to create complex string literals.
I have added an example for variable interpolation with a single word by enclosing the
variable within curly braces like {$variable_name} below.
Variable interpolation in double-quoted string
The following code shows an example for interpolating variables into a string
literal that is enclosed in double quotes. In this example, I have a string variable
containing the value ‘PHPPOT’ which is interpolated into the echo statement.
In this program, I interpolated the variable in a single-quoted and double-quoted
string. This is is to showcase that the variable interpolation in PHP works only with
double-quoted strings.
<?php
$name = "PHPPOT";
echo "I am reading $name"; // output: I am reading PHPPOT
echo 'I am reading $name'; // output: I am reading $name
?>
Variable interpolation with heredoc
The code has a heredoc statement. In this statement, I added multiple lines of
string data and interpolated the $name variable into it. While printing this statement
the PHP variable is parsed to print the value.
After variable parsing, the heredoc statement will be printed with the line
breaks as specified.
<?php
$name = "PHPPOT";
$myDoc = <<< EOD I am reading $name
to know all about PHP
EOD;
echo $myDoc;
?>

Accessing Individual Characters


A string is a sequence of characters. It may contain integers or even special symbols.
Every character in a string is stored at a unique position represented by a unique index value.
Here are some approaches to read each character of a string in PHP
 Using str_split() method – The str_split() method
 Using strlen() method – The strlen() method
Using str_split() method – The str_split() method
Using str_split() method – The str_split() method is used to split the specified
string variable into an array of values, each of which is mapped to an index value
beginning with 0. This method converts the input string into an array.
str_split(str)
PHP foreach loop iteration can then be done over the array values, each of which
element belongs to a character of the string. The values are then printed with a space
in between each.
Example:
<?php

// Declaring string variable


$str = "Hi!GFG User.";

echo("Original string : ");


echo($str . "</br>");

$array = str_split($str);
echo("Characters : ");

foreach($array as $val){
echo($val . " ");
}
?>
Output:
Original string : Hi!GFG User.
Characters : H i ! G F G U s e r .
Using strlen() method – The strlen() method
Using strlen() method – The strlen() method is used to compute the length of the
specified string in PHP. A for loop iteration is applied using the length of the string, and
the ith index character is printed each time. The time complexity is the same as the
previous method. However, no extra space is required to store the string in the form of the
array object.
strlen(str)
Example:
<?php

// Declaring string variable


$str = "Hi!GFG User.";

echo("Original string : ");


echo($str."</br>");
echo("Characters : ");

// Iterating over the string


$len = strlen($str);

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


echo ($str[$i]." ");
}

?>
Output:
Original string : Hi!GFG User.
Characters : H i ! G F G U s e r .

Cleaning Strings
We are given a string and the task is to remove special characters from
string str in PHP.
Below are the approaches to remove special characters from string in PHP:
 Using str_replace() Method
 Using str_ireplace() Method

Using str_replace() Method


The str_replace() method is used to remove all the special characters from the
given string str by replacing these characters with the white space (” “).
Syntax:
str_replace( $searchVal, $replaceVal, $subjectVal, $count )
Example: This example illustrates the use of the str_replace() function to remove the
special characters from the string.
<?php
// PHP program to Remove
// Special Character From String

// Function to remove the special


function RemoveSpecialChar($str) {

// Using str_replace() function


// to replace the word
$res = str_replace( array( '\'', '"',
',' , ';', '<', '>' ), ' ', $str);

// Returning the result


return $res;
}

// Given string
$str = "Example,to remove<the>Special'Char;";

// Function calling
$str1 = RemoveSpecialChar($str);

// Printing the result


echo $str1;
?>
Output:
Example to remove the Special Char
Using str_ireplace() Method
The str_ireplace() method is used to remove all the special characters from
the given string str by replacing these characters with the white space (” “). The
difference between str_replace and str_ireplace is that str_ireplace is case-
insensitive.
Syntax:
str_ireplace( $searchVal, $replaceVal, $subjectVal, $count )
Example: This example illustrates the use of the str_ireplace() method to remove
all the special characters from the string.
<?php
// PHP program to Remove
// Special Character From String

// Function to remove the special


function RemoveSpecialChar($str){

// Using str_ireplace() function


// to replace the word
$res = str_ireplace( array( '\'', '"',
',' , ';', '<', '>' ), ' ', $str);

// returning the result


return $res;
}

// Given string
$str = "Example,to remove<the>Special'Char;";

// Function calling
$str1 = RemoveSpecialChar($str);

// Printing the result


echo $str1;
?>
Output:
Example to remove the Special Char

Encoding and Escaping


Encoding
The base64_encode() function is an inbuilt function in PHP that is used to encode
data with MIME base64. MIME (Multipurpose Internet Mail Extensions) base64 is used to
encode the string in base64. The base64_encoded data takes 33% more space than the
original data.
Syntax:
string base64_encode( $data )
Parameters: This function accepts single parameter $data which is mandatory. It is used
to specify the string encoding.
Return value: This function returns the encoded string in base64 on success or returns
False in case of failure. The below programs illustrate the base64_encode() function in
PHP.
Example
<?php

// Program to illustrate base64_encode()


// function
$str = 'GFG, A computer Science Portal For Geeks';
echo base64_encode($str). "\n";

$str = '';
echo base64_encode($str). "\n";

$str = 1;
echo base64_encode($str). "\n";

$str = '@#$';
echo base64_encode($str). "\n";
?>
Output:
R0ZHLCBBIGNvbXB1dGVyIFNjaWVuY2UgUG9ydGFsIEZvciBHZWVrcw==

MQ==
QCMk
Escaping
Escape characters in PHP are special characters that allow you to include non-
printable characters, represent special characters, or format strings in a way that
might be challenging with regular characters alone. They are preceded by a
backslash \. In this article, we'll explore how to use escape characters in PHP,
covering various scenarios and providing detailed descriptions with examples.
Method 1: Escaping Special Characters
Escape characters are often used to include special characters within strings
without disrupting the code. For example, include a double quote within a double-
quoted string.
<?php

$str = "This is a \"quote\" inside a string.";


echo $str;

?>
Output
This is a "quote" inside a string.
Here, the escape character \" allows the double quote to be part of the string without
ending it.
Method 2: Newline and Tab Characters
Escape characters are handy for introducing newlines (\n) and tabs (\t) within
strings.
<?php
$str = "Line 1\nLine 2\nLine 3\n";
echo $str;
$str2 = "Name\tAge\tCity";
echo $str2;
?>

Output
Line 1
Line 2
Line 3
Name Age City
Method 3: Single Quoted Strings
Escape characters behave differently in single-quoted strings compared to double-
quoted strings. In single-quoted strings, only the backslash itself (\\) and the single
quote (\') need to be escaped.
<?php

$str = 'This is a single quote: \'';


echo $str;

?>
Output
This is a single quote: '
Method 4: Heredoc and Nowdoc Syntax
PHP offers Heredoc and Nowdoc syntaxes for working with multi-line strings,
which can include escape characters for various purposes. Heredoc syntax behaves
similarly to double-quoted strings, while Nowdoc syntax behaves similarly to single-
quoted strings.
Example:
1. Heredoc Syntax:
Heredoc syntax allows the inclusion of escape characters and variable
interpolation within a multi-line string.
<?php
$variable = "example";
$heredocString = <<<EOD
This is an "example" of a Heredoc string.
It can include newlines \n and tabs \t.
Variable interpolation: $variable
EOD;
echo $heredocString;
?>
Output
This is an "example" of a Heredoc string.
It can include newlines
and tabs .
Variable interpolation: example

2. Nowdoc Syntax:
Nowdoc syntax is similar to Heredoc but behaves like single-quoted strings,
meaning it does not parse escape characters or variable interpolation.
<?php
$nowdocString = <<<'EOD'
This is an 'example' of a Nowdoc string.
It treats newlines \n and tabs \t as literal text.
Variable interpolation: $variable
EOD;
echo $nowdocString;
?>
Output
This is an 'example' of a Nowdoc string.
It treats newlines \n and tabs \t as literal text.
Variable interpolation: $variable

Comparing Strings
Comparing two strings is one of the most commonly used string operation in
programming and web development practices. The strcmp() is an inbuilt function in
PHP and is used to compare two strings. This function is case-sensitive which points
that capital and small cases will be treated differently, during comparison. This
function compares two strings and tells us that whether the first string is greater or
smaller than the second string or equals to the second string.
Syntax:
strcmp($string1, $string2)
Parameters: This function accepts two parameters which are described below:
1. $string1 (mandatory): This parameter refers to the first string to be used in
the comparison
2. $string2 (mandatory): This parameter refers to the second string to be used in
the comparison.
Return Values: The function returns a random integer value depending on the
condition of match, which is given by:
 Returns 0 if the strings are equal.
 Returns a negative value (<0), if $string2 is greater than $string1.
 Returns a positive value (>0) if $string1 is greater than $string2.
In this code we will try to understand the working of strcmp() function:
<?php
// PHP program to illustrate the working of strcmp()
$string1 = "Welcome to GFG";
$string2 = "Welcome to GeeksforGeeks";
$string3 = "Welcome to GFG";

// In this case both the strings are equal


print_r(strcmp($string1, $string3));
echo "\n";

// In this case the first is greater


print_r(strcmp($string2, $string1));
echo "\n";

// In this case the second is greater


print_r(strcmp($string3, $string2))

?>
Output:
0
31
-31
Manipulating and Searching Strings
Manipulating
String manipulation is a fundamental aspect of programming, and PHP provides
a powerful set of tools and functions to work with strings effectively. In PHP, strings
are a sequence of characters enclosed in quotes, and they can be manipulated in
various ways to perform tasks such as modifying, searching, extracting, and formatting
textual data.
Various String Manipulation Functions in PHP
PHP provides a variety of built-in functions for string manipulation. Here are some
commonly used functions of string manipulation in php:
 strlen():
Returns the length of a string.
 substr():
Extracts a substring from a string based on a specified start and optionally end position.
 str_replace():
Replaces all occurrences of a substring with another substring within a string.
 strpos():
Searches for the position of the first occurrence of a substring within a string.
 str_split():
Converts a string into an array of characters.
 strtolower():
Converts a string to lowercase.
 strtoupper():
Converts a string to uppercase.
 trim():
Removes whitespace or specified characters from the beginning and end of a string.
 explode():
Splits a string into an array by a specified delimiter.
 implode():
Joins elements of an array into a string using a specified delimiter.
 sprintf():
Formats a string by substituting placeholders with corresponding values.
 ucfirst():
Converts the first character of a string to uppercase.
 ucwords():
Converts the first character of each word in a string to uppercase.
These functions allow developers to perform tasks like finding and replacing substrings,
extracting parts of a string, manipulating a case, splitting and joining strings, formatting strings
with dynamic values, and more.
Here's an example program that demonstrates the usage of various string manipulation
functions in PHP to validate their functionality:
<?php
// Sample string
$string = "Hello, World!";

// Validate strlen()
$length = strlen($string);
echo "Length of the string: ". $length. "\n";

// Validate substr()
$subString = substr($string, 7);
echo "Substring from position 7: " . $subString. "\n";

// Validate str_replace()
$newString = str_replace("World", "PHP", $string);
echo "Replaced string: ". $newString. "\n";

// Validate strpos()
$position = strpos($string, ",");
echo "Position of the comma: ". $position. "\n";

// Validate str_split()
$charArray = str_split($string);
echo "Character array: ";
print_r($charArray);

// Validate strtolower()
$lowercaseString = strtolower($string);
echo "Lowercase string: ". $lowercaseString. "\n";
// Validate strtoupper()
$uppercaseString = strtoupper($string);
echo "Uppercase string: ". $uppercaseString. "\n";

// Validate trim()
$trimmedString = trim(" Hello, World! ");
echo "Trimmed string: ". $trimmedString. "\n";

// Validate explode()
$wordsArray = explode(" ", $string);
echo "Exploded array: ";
print_r($wordsArray);

// Validate implode()
$joinedString = implode("-", $wordsArray);
echo "Joined string: ". $joinedString. "\n";

// Validate sprintf()
$formattedString = sprintf("Today is %s, %d %s", "Monday", 5, "June");
echo "Formatted string: ". $formattedString. "\n";

// Validate ucfirst()
$ucFirstString = ucfirst($string);
echo "String with the first character capitalized: ". $ucFirstString. "\n";

// Validate ucwords()
$ucWordsString = ucwords($string);
echo "String with each word's first character capitalized: ". $ucWordsString. "\n";
?>
Searching
PHP gives you many useful functions for searching strings.
 strstr() for finding out whether some text is in a string
 strpos() and strrpos() for finding the position of some text in a string
 substr_count() for finding out how many times some text appears in a string

PHP’s strstr() function simply takes a string to search, and a chunk of text to search for. If the
text was found, it returns the portion of the string from the first character of the match up to the
end of the string:
$myString = 'Hello, there!';
echo strstr( $myString, 'llo' ); // Displays "llo, there!"

If the text wasn’t found then strstr() returns false. You can use this fact to determine if the text
chunk was in the string or not:

$myString = 'Hello, there!';


if ( strstr( $myString, 'Goodbye' ) ) {
echo "Text found";
} else {
echo "Text not found";
}
The above code displays:

Text not found


Finding the position of a match: strpos() and strrpos()
strpos() takes the same 2 arguments as strstr(). However, rather than returning a
portion of the string, it returns the index of the first character of the matched text in the
string:
$myString = 'Hello, there!';
echo strpos( $myString, 'llo' ); // Displays "2"

In the above code, strpos() finds the text 'llo' in the target string starting at the 3rd
character, so it returns 2. (Remember that character index positions in strings start from 0,
not 1.) Be careful when using strpos() to check for the existence of a match. The following
code incorrectly displays “Not found”, because strpos() returns 0, which is equivalent
to false in PHP:
$myString = 'Hello, there!';
if ( strpos( $myString, 'Hello' ) ) {
echo "Found";
} else {
echo "Not found";
}
To fix this, make sure you test explicitly for false by using the === or !== operator. The
following code correctly displays “Found”:
$myString = 'Hello, there!';
if ( strpos( $myString, 'Hello' ) !== false ) {
echo "Found";
} else {
echo "Not found";
}

You can pass a third argument to strpos() to specify the index position from which to begin
the search:
$myString = 'Hello, there!';
echo strpos( $myString, 'e' ) . '<br />'; // Displays "1"
echo strpos( $myString, 'e', 2 ) . '<br />'; // Displays "9"

The strrpos() function is very similar to strpos(). The only difference is that it finds
the last match in the string instead of the first:
$myString = 'Hello, there!';
echo strpos( $myString, 'e' ) . "<br />"; // Displays "1"
echo strrpos( $myString, 'e' ) . "<br />"; // Displays "11"
As with strstr(), the strpos() and strrpos() functions are case sensitive. Their case-insensitive equivalents
are stripos() and strripos() respectively.
Counting matches with substr_count()
You can use PHP’s substr_count() function to find the number of times a chunk of
text appears in the target string:
$myString = 'Short stories';
echo substr_count( $myString, 'or' ); // Displays "2"
As with strpos() and strrpos(), you can pass an optional third argument: the index position to
begin the search. For example:
$myString = 'Short stories';
echo substr_count( $myString, 'or', 6 ); // Displays "1"
You can also pass an optional fourth argument: the number of characters after the offset
position in which to search for the text. For example:
echo substr_count( $myString, 'or', 0, 10 ) . '<br />'; // Displays "2"
echo substr_count( $myString, 'or', 0, 5 ) . '<br />'; // Displays "1"

Introduction to Regular expression


Regular expression allows you to search a specific string inside another string. Even we
can replace one string by another string and also split a string into multiple chunks. They use
arithmetic operators (+, -, ^) to create complex expressions.
PHP offers two sets of regular expression functions:
1. POSIX Regular Expression
2. PERL Style Regular Expression
POSIX Regular Expression
The structure of POSIX regular expression is similar to the typical arithmetic expression:
several operators/elements are combined together to form more complex expressions. The
simplest regular expression is one that matches a single character inside the string. For example
- "g" inside the toggle or cage string. Let's introduce some concepts being used in POSIX
regular expression:
Brackets
Brackets [] have a special meaning when they are used in regular expressions. These are
used to find the range of characters inside it.

Expression Description

[0-9] It matches any decimal digit 0 to 9.

[a-z] It matches any lowercase character


from a to z.

It matches any uppercase character


[A-Z]
from A to Z.

It matches any character from


[a-Z]
lowercase a to uppercase Z.
The above ranges are commonly used. You can use the range values according to your need, like
[0-6] to match any decimal digit from 0 to 6.
PHP Regexp POSIX Function
PHP provides seven functions to search strings using POSIX-style regular expression –

Function Description

It searches a string pattern inside


ereg() another string and returns true if the
pattern matches otherwise return false.

It searches a string pattern inside the


ereg_replace() other string and replaces the matching
text with the replacement string.

It searches for a pattern inside the other


string and returns the length of matched
eregi()
string if found otherwise returns false. It
is a case insensitive function.

This function works same


as ereg_replace() function. The only
eregi_replace()
difference is that the search for pattern
of this function is case insensitive.

The split() function divide the string


split()
into array.

It is similar to split() function as it also


spliti() divides a string into array by regular
expression.

It creates a regular expression for case


insensitive match and returns a valid
Sql_regcase()
regular expression that will match
string.
PERL Style Regular Expression
Perl-style regular expressions are much similar to POSIX. The POSIX syntax can be used
with Perl-style regular expression function interchangeably. The quantifiers introduced in POSIX
section can also be used in PERL style regular expression.
Metacharacters
A metacharacter is an alphabetical character followed by a backslash that gives a special
meaning to the combination.
For example - '\d' metacharacter can be used search large money sums: /([\d]+)000/. Here /d will
search the string of numerical character.
Below is the list of metacharacters that can be used in PERL Style Regular Expressions –

Character Description

. Matches a single character

It matches a whitespace character like space,


\s
newline, tab.

\S Non-whitespace character

\d It matches any digit from 0 to 9.

\D Matches a non-digit character.

Matches for a word character such as - a-z, A-


\w
Z, 0-9, _

\W Matches a non-word character.

[aeiou] It matches any single character in the given set.

It matches any single character except the


[^aeiou]
given set.

(foo|baz|bar) Matches any of the alternatives specified.

Modifiers
There are several modifiers available, which makes the work much easier with a regular
expression. For example - case-sensitivity or searching in multiple lines, etc.
Below is the list of modifiers used in PERL Style Regular Expressions –

Character Description

i Makes case insensitive search

m It specifies that if a string has a carriage


return or newline characters, the $ and ^
operator will match against a newline
boundary rather than a string boundary.

o Evaluates the expression only once

It allows the use of .(dot) to match a


s
newline character

This modifier allows us to use whitespace


x
in expression for clarity.

g It globally searches all matches.

It allows the search to continue even after


cg
the global match fails.

Advantage and uses of Regular Expression


Regular expression is used almost everywhere in current application programming.
Below some advantages and uses of regular expressions are given:
1. Regular expression helps the programmers to validate text string.
2. It offers a powerful tool to analyze and search a pattern as well as to modify the text
string.
3. By using regexes functions, simple and easy solutions are provided to identify the
patterns.
4. Regexes are helpful for creating the HTML template system recognizing tags.
5. Regexes are widely used for browser detection, form validation, spam filtration, and
password strength checking.
6. It is helpful in user input validation testing like email address, mobile number, and IP
address.
7. It helps in highlighting the special keywords in file based upon the search result or input.
8. Metacharacters allow us to create more complex patterns.

You might also like