Unit III PHP
Unit III PHP
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);
Syntax:
function function_name(){
executable code;
}
Example:
<?php
function funcGeek()
{
echo "This is Students";
}
?>
Output:
This is Students
Example:
<?php
?>
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
?>
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
?>
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
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
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>";
}
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'.
?>
function getUserInfo() {
$name = "XYZ";
$age = 20;
$email = "[email protected]";
?>
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;
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
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
?>
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;
?>
$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
?>
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
// Given string
$str = "Example,to remove<the>Special'Char;";
// Function calling
$str1 = RemoveSpecialChar($str);
// Given string
$str = "Example,to remove<the>Special'Char;";
// Function calling
$str1 = RemoveSpecialChar($str);
$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
?>
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
?>
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";
?>
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:
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"
Expression Description
Function Description
Character Description
\S Non-whitespace character
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