PHP Unit 2
PHP Unit 2
Contents
Function ........................................................................................................................................................ 3
Advantage of function:........................................................................................................................ 3
Function Definition/Creating a Function .................................................................................... 3
Function call/Calling a function ...................................................................................................... 4
Variable Scope: ........................................................................................................................................... 4
Local variable ......................................................................................................................................... 4
Global variable ....................................................................................................................................... 5
Static .......................................................................................................................................................... 6
Function Parameters or Arguments .................................................................................................. 6
Passing Parameters by value/Call by value ............................................................................... 7
Passing Parameters by Reference .................................................................................................. 7
Setting Default Values for Function parameter ........................................................................ 8
Returning Values from Functions ....................................................................................................... 8
Variable Function ...................................................................................................................................... 9
Type Hinting ................................................................................................................................................ 9
Anonymous function .............................................................................................................................. 10
PHP String .................................................................................................................................................. 11
Single Quoted ....................................................................................................................................... 11
Double Quoted ..................................................................................................................................... 11
Heredoc .................................................................................................................................................. 11
Accessing Individual Characters ....................................................................................................... 12
Cleaning Strings ....................................................................................................................................... 12
Removing Whitespace ...................................................................................................................... 12
Changing Case ...................................................................................................................................... 13
Encoding and Escaping ......................................................................................................................... 14
HTML ....................................................................................................................................................... 14
Entity-quoting all special characters .......................................................................................... 14
Entity-quoting only HTML syntax characters ......................................................................... 14
Removing HTML tags ........................................................................................................................ 15
Extracting meta tags .......................................................................................................................... 15
Comparing Strings .................................................................................................................................. 16
PHP Unit 2 2 GSC BCA
Exact Comparisons............................................................................................................................. 16
Approximate Equality ....................................................................................................................... 17
Manipulating and Searching Strings ................................................................................................ 18
Substrings .............................................................................................................................................. 18
Miscellaneous String Functions .................................................................................................... 20
Decomposing a String ....................................................................................................................... 21
String-Searching Functions ............................................................................................................ 22
Regular Expression ................................................................................................................................. 25
Regular Expression Functions ....................................................................................................... 25
Regular expression quantifiers ..................................................................................................... 26
Character classes ................................................................................................................................ 26
Anchors................................................................................................................................................... 26
PHP Unit 2 3 GSC BCA
Function
A function is a block of code written in a program to perform some specific task. They
take information as parameter, execute a block of statements or perform operations on
this parameters and returns the result.
Advantage of function:
Code Reusability: PHP functions are defined only once and can be invoked many
times, like in other programming languages.
Less Code: It saves a lot of code because you don't need to write the logic many
times.
Easy to understand: PHP functions separate the programming logic. So it is
easier to understand the flow of the application.
Easier error detection: Since, our code is divided into functions, we can easily
detect in which function, and the error could lie and fix them fast and easily.
Easily maintained: 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.
Syntax:
function function_name()
{
executable code;
}
Example:
<?php
function writeMessage()
{
echo "Hello world!";
}
?>
Example
<?php
function writeMessage()
{
echo "Hello world!";
}
writeMessage();
?>
Variable Scope:
Scope of variable is the part of PHP script where the variable can be accessed or used.
PHP supports three different scopes for a variable. These scopes are-
1. Local
2. Global
3. Static
Local variable
A variable declared within the function has local scope. That means this variable is only
used within the function body. This variable is not used outside the function.
function localscope()
{
$var = 5; //local scope
PHP Unit 2 5 GSC BCA
echo '<br> The value of $var inside the function is: '. $var;
}
localscope(); // call the function
echo '<br> The value of $var inside the function is: '. $var;
The output will be:
Global variable
If a variable is defined outside of the function, then the variable scope is global. By
default, a global scope variable is only available to code that runs at global level. That
means, it is not available inside a function.
<?php
$globalscope = 20;
function localscope()
{
echo '<br> The value of global scope variable is :'.$globalscope;
}
localscope(); // call the function
echo '<br> The value of $globalscope outside the function is: '. $globalscope;
?>
To access a global variable from within a function global statement is used. The global
statement import a variable from global scope to local scope.
$globalscope = 20;
function localscope()
{
global $globalscope;
echo '<br> The value of global scope variable is :'.$globalscope;
}
localscope();
echo '<br> The value of $globalscope outside the function is: '. $globalscope;
Static
Generally when function is completed, all of its variable is wiped out. In case a function
executes many times, each time the function start with fresh copy of variable and the
previous value has no effect. Sometimes it can be required to not delete the local
variable. This variable may be required to use for further task. Static keyword is used to
retain the variable. Note that the scope of static is local. Static variable is assigned only
with predetermined values.
function localscope()
{
static $var = 5; //local scope
echo '<br> The value of static variable $var inside the function is: '. $var;
$var++;
}
localscope(); // call the function
localscope(); // call the function
localscope(); // call the function
// using $var outside the function will generate an error
echo '<br> The value of $var inside the function is: '. $var;
There are two different ways to pass parameters to a function. The first, and more
common, is by value. The other is by reference.
PHP Unit 2 7 GSC BCA
Example:
<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
addFunction(10, 20);
?>
Output:
<?php
function addFive($num) {
$num += 5;
}
function addSix(&$num) {
$num += 6;
}
$orignum = 10;
addFive( $orignum );
addSix( $orignum );
echo "Original Value is $orignum<br />";
?>
Original Value is 10
Original Value is 16
PHP Unit 2 8 GSC BCA
Example:
<?php
function sayHello($name="Sonoo"){
echo "Hello $name<br/>";
}
sayHello("Rajesh");
sayHello();//passing no value
sayHello("John");
?>
Output:
Hello Rajesh
Hello Sonoo
Hello John
Example:
<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
return $sum;
}
$return_value = addFunction(10, 20);
Variable Function
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.
Example
<?php
function add($x, $y){
echo $x+$y;
}
$var="add";
$var(10,20);
?>
Output
This will produce following result.
30
Type Hinting
Type hinting is a concept that provides hints to function for the expected data type of
arguments.
For example, If we want to add an integer while writing the add function, we had
mentioned the data type (integer in this case) of the parameter. While calling the
function we need to provide an argument of integer type only. If you provide data of any
other type, it will throw an error with clear instructions that the value of an integer type
is needed.
Example:
<?php
function add(array $numbers){
$sum=0;
foreach($numbers as $item){
$sum=$sum+$item;
}
echo $sum;
}
add(array(10,10));
?>
Output: 20
Anonymous function
Anonymous function is a function without any user defined name. Such a function is
also called closure or lambda function. Most common use of anonymous function is to
create an inline callback function.
Syntax
Example
<?php
Output
PHP String
PHP string is a sequence of characters. Everything inside quotes, single (‘ ‘) and double
(” “) in PHP is treated as a string. There are 3 ways to specify a string literal in PHP.
1. single quoted
2. double quoted
3. heredoc syntax
Single Quoted
This type of string does not process special characters inside quotes.
<?php
$str=”PHP”;
echo ‘Hello, $str’;
?>
Double Quoted
Unlike single-quote strings, double-quote strings in PHP are capable of processing
special characters.
<?php
$str="PHP";
echo “Hello, $str”;
?>
Escape Sequence
Heredoc
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.
PHP Unit 2 12 GSC BCA
<?php
$input = <<<testHeredoc
Welcome to PHP.
Started writing programme in PHP!.
I am enjoying this.
testHeredoc;
echo $input;
?>
Output:
Welcome to PHP.
Started writing programme in PHP!.
I am enjoying this.
You can use the string offset syntax on a string to address individual characters:
$string = 'Hello';
for ($i=0; $i < strlen($string); $i++) {
printf("The %dth character is %s\n", $i, $string{$i});
}
Cleaning Strings
Often, the strings we get from files or users need to be cleaned up before we can use
them. Two common problems with raw data are the presence of extraneous whitespace
and incorrect capitalization (uppercase versus lowercase).
Removing Whitespace
You can remove leading or trailing whitespace with the trim(), ltrim(), and rtrim()
functions:
trim() returns a copy of string with whitespace removed from the beginning and the
end. ltrim() (the l is for left) does the same, but removes whitespace only from the start
of the string. rtrim() (the r is for right) removes whitespace only from the end of the
string.
For example:
Given a line of tab-separated data, use the charlist argument to remove leading or
trailing whitespace without deleting the tabs:
Changing Case
$string1 = "FRED flintstone";
$string2 = "barney rubble";
print(strtolower($string1));
print(strtoupper($string1));
print(ucfirst($string2));
print(ucwords($string2));
print(ucwords(strtolower($string1)));
Output:
fred flintstone
FRED FLINTSTONE
Barney rubble
Barney Rubble
Fred Flintstone
PHP Unit 2 14 GSC BCA
HTML
Special characters in HTML are represented by entities such as & and <. There
are two PHP functions that turn special characters in a string into their entities: one for
removing HTML tags, and one for extracting only meta tags.
Example:
<?php
$str = '<a href="https://www.w3schools.com">Go to w3schools.com</a>';
echo htmlentities($str);
?>
<a href="https://www.w3schools.com">Go to
w3schools.com</a>
Example:
<?php
$str = "This is some <b>bold</b> text.";
echo htmlspecialchars($str);
?>
<!DOCTYPE html>
<html>
<body>
This is some <b>bold</b> text.
</body>
</html>
Example 1:
$input = '<p>Howdy, "Cowboy"</p>';
$output = strip_tags($input);
Example 2:
$metaTags = get_meta_tags('http://www.example.com/');
Comparing Strings
PHP has two operators and six functions for comparing strings to each other.
Exact Comparisons
You can compare two strings for equality with the == and === operators. These
operators differ in how they deal with non-string operands. The == operator casts non-
string operands to strings, so it reports that 3 and "3" are equal. The === operator does
not cast, and returns false if the types of the arguments differ.
$o1 = 3;
$o2 = "3";
if ($o1 == $o2) {
echo("== returns A<br>");
}
if ($o1 === $o2) {
echo("=== returns B<br>");
}
Output: == returns A
The comparison operators (<, <=, >, >=) also work on strings:
$him = "Fred";
$her = "Wilma";
if ($him < $her) {
print "$him comes before $her in the alphabet.\n";
}
However, the comparison operators give unexpected results when comparing strings
and numbers:
When one argument to a comparison operator is a number, the other argument is cast
to a number. This means that "PHP Rocks" is cast to a number, giving 0 (since the string
does not start with a number). Because 0 is less than 5, PHP prints "PHP Rocks < 5".
To explicitly compare two strings as strings, casting numbers to strings if necessary, use
the strcmp( ) function:
PHP Unit 2 17 GSC BCA
The function returns a number less than 0 if string_1 sorts before string_2, greater than
0 if string_2 sorts before string_1, or 0 if they are the same:
Output: 1
$n = strcasecmp("Fred", "frED"); // $n is 0
Approximate Equality
PHP provides several functions that let you test whether two strings are approximately
equal: soundex( ) , metaphone( ), similar_text(), and levenshtein( ).
$soundex_code = soundex($string);
$metaphone_code = metaphone($string);
$in_common = similar_text($string_1, $string_2 [, $percentage ]);
$similarity = levenshtein($string_1, $string_2);
$similarity = levenshtein($string_1, $string_2 [, $cost_ins, $cost_rep, $cost_del ]);
To see whether two strings are approximately equal with these algorithms, compare
their pronunciations. You can compare Soundex values only to Soundex values and
Metaphone values only to Metaphone values. The Metaphone algorithm is generally
more accurate, as the following example demonstrates:
Example:
$known = "Fred";
$query = "Phred";
if (soundex($known) == soundex($query)) {
print "soundex: $known sounds like $query<br>";
} else {
print "soundex: $known doesn't sound like $query<br>";
}
if (metaphone($known) == metaphone($query)) {
print "metaphone: $known sounds like $query<br>";
} else {
print "metaphone: $known doesn't sound like $query<br>";
}
Output:
soundex: Fred doesn't sound like Phred
metaphone: Fred sounds like Phred
PHP Unit 2 18 GSC BCA
similar_text( )
The similar_text( ) function returns the number of characters that its two string
arguments have in common. The third argument, if present, is a variable in which to
store the commonality as a percentage:
The Levenshtein algorithm calculates the similarity of two strings based on how many
characters you must add, substitute, or remove to make them the same. For instance,
"cat" and "cot" have a Levenshtein distance of 1, because you need to change only one
character (the "a" to an "o") to make them the same:
Substrings
substr( )
If you know where in a larger string the interesting data lies, you can copy it out with
the substr( ) function:
The start argument is the position in string at which to begin copying, with 0 meaning
the start of the string. The length argument is the number of characters to copy (the
default is to copy until the end of the string).
Example:
substr_count( )
To learn how many times a smaller string occurs in a larger one, use substr_count( ) :
Example:
substr_replace( )
The substr_replace( ) function permits many kinds of string modifications:
The function replaces the part of original indicated by the start (0 means the start of the
string) and length values with the string new. If no fourth argument is given,
substr_replace( ) removes the text from start to the end of the string.
Example:
A negative value for start indicates the number of characters from the end of the string
from which to start the replacement:
A negative length indicates the number of characters from the end of the string at which
to stop deleting:
$string = strrev(string);
For example:
The str_repeat( ) function takes a string and a count and returns a new string
consisting of the argument string repeated count times:
The str_pad( ) function pads one string with another. Optionally, you can say what
string to pad with, and whether to pad on the left, right, or both:
[ Fred Flintstone]
[ Fred Flintstone ]
Decomposing a String
PHP provides several functions to let you break a string into smaller components. In
increasing order of complexity, they are explode( ), strtok( ), and sscanf( ).
Data often arrives as strings, which must be broken down into an array of values. For
instance, you might want to separate out the comma-separated fields from a string such
as "Fred,25,Wilma". In these situations, use the explode( ) function:
The first argument, separator, is a string containing the field separator. The second
argument, string, is the string to split. The optional third argument, limit, is the
maximum number of values to return in the array. If the limit is reached, the last
element of the array contains the remainder of the string:
$input = 'Fred,25,Wilma';
$fields = explode(',', $input);
// $fields is array('Fred', '25', 'Wilma')
$fields = explode(',', $input, 2);
// $fields is array('Fred', '25,Wilma')
The implode( ) function does the exact opposite of explode( )—it creates a large string
from an array of smaller strings:
The first argument, separator, is the string to put between the elements of the second
argument, array. To reconstruct the simple comma-separated value string, simply say:
Tokenizing
The strtok( ) function lets you iterate through a string, getting a new chunk (token)
each time. The first time you call it, you need to pass two arguments: the string to iterate
over and the token separator:
To retrieve the rest of the tokens, repeatedly call strtok( ) with only the separator:
$next_chunk = strtok(separator);
PHP Unit 2 22 GSC BCA
$string = "Fred,Flintstone,35,Wilma";
$token = strtok($string, ",");
while ($token !== false) {
echo("$token<br>");
$token = strtok(",");
}
Output:
Fred
Flintstone
35
Wilma
sscanf( )
Output:
Array
(
[0] => Fred
[1] => Flintstone
[2] => 35
)
Pass references to variables to have the fields stored in those variables. The number of
fields assigned is returned:
String-Searching Functions
Several functions find a string or character within a larger string. They come in three
families: strpos( ) and strrpos( ), which return a position; strstr( ), strchr( ), and friends,
which return the string they find; and strspn( ) and strcspn( ), which return how much
of the start of the string matches a mask.
PHP Unit 2 23 GSC BCA
The strpos( ) function finds the first occurrence of a small string in a larger string:
The strrpos( ) function finds the last occurrence of a character in a string. It takes the
same arguments and returns the same type of value as strpos( ).
For instance:
$record = "Fred,Flintstone,35,Wilma";
$pos = strrpos($record, ","); // find last comma
echo("The last comma in the record is at position $pos");
If you pass a string as the second argument to strrpos( ), only the first character is
searched for. To find the last occurrence of a multicharacter string, reverse the strings
and use strpos( ):
The strstr( ) function finds the first occurrence of a small string in a larger string and
returns from that small string on. For instance:
$record = "Fred,Flintstone,35,Wilma";
If you thought strrchr( ) was esoteric, you haven’t seen anything yet. The strspn( ) and
strcspn( ) functions tell you how many characters at the beginning of a string are
comprised of certain characters:
For example, this function tests whether a string holds an octal number:
The c in strcspn( ) stands for complement—it tells you how much of the start of the
string is not composed of the characters in the character set. Use it when the number of
interesting characters is greater than the number of uninteresting characters. For
example, this function tests whether a string has any NUL-bytes, tabs, or carriage
returns:
Decomposing URLs
$array = parse_url(url);
For example:
$bits = parse_url('http://me:secret@example.com/cgi-bin/board?user=fred);
print_r($bits);
Output:
Array
(
[scheme] => http
[host] => example.com
[user] => me
[pass] => secret
[path] => /cgi-bin/board
[query] => user=fred
)
PHP Unit 2 25 GSC BCA
Regular Expression
Regular expressions commonly known as a regex (regexes) are a sequence of characters
describing a special search pattern in the form of text string.
Function Description
preg_match() Returns 1 if the pattern was found in the string and 0 if not
preg_match_all() Returns the number of times the pattern was found in the string,
which may also be 0
preg_replace() Returns a new string where matched patterns have been replaced
with another string
Example:
Some characters have special meanings in regular expressions. For instance, a caret (^)
at the beginning of a regular expression indicates that it must match the beginning of
the string (or, more precisely, anchors the regular expression to the beginning of the
string):
Similarly, a dollar sign ($) at the end of a regular expression means that it must match
the end of the string (i.e., anchors the regular expression to the end of the string):
If you want to match one of these special characters (called a metacharacter), you have
to escape it with a backslash:
Quantifier Meaning
? 0 or 1
* 0 or more
+ 1 or more
{n} Exactly n times
{n,m} At least n, no more than m times
{ n ,} At least n times
Character classes
Anchors
An anchor limits a match to a particular location in the string (anchors do not match
actual characters in the target string). Table 4-8 lists the anchors supported by regular
expressions.
Anchor Matches
^ Start of string
$ End of string
[[:<:]] Start of word
PHP Unit 2 27 GSC BCA