Chapter 5:-Function and Strings Function
PHP functions are similar to other programming
languages. A function is a piece of code which takes one more input in the form
of parameter and does some processing and returns a value.
Creating PHP Function
Its very easy to create your own PHP function.
Suppose you want to create a PHP function which will simply write a simple
message on your browser when you will call it. Following example creates a
function called writeMessage() and then calls it just after creating it.
Note that while creating a function its name
should start with keyword function and all the PHP code should be put inside {
and } braces as shown in the following example below
<html>
<body>
<?php
/*
Defining a PHP Function */
function writeMessage()
{
echo "You are really a nice person, Have a
nice time!";
}
/* Calling a PHP Function */
writeMessage();
?>
</body>
</html>
PHP Functions with Parameters
PHP gives you option to pass your parameters
inside a function. You can pass as many as parameters your like. These
parameters work like variables inside your function. Following example takes
two integer parameters and add them together and then print them.
<html>
<body>
<?php
function addFunction($num1, $num2)
{
$sum = $num1 + $num2;
echo "Sum of the two numbers is :
$sum";
}
addFunction(10, 20);
?>
</body>
</html>
PHP Default Argument Values Function
PHP allows you to define C++ style default
argument values. In such case, if you don't pass any value to the function, it
will use default argument value.
<?php
function sayHello($name="Ram"){
echo "Hello $name<br/>";
}
sayHello("Sonoo");
sayHello();//passing no value
sayHello("Vimal");
?>
Output:-
Hello Sonoo
Hello Ram
Hello Vimal
PHP Function Arguments
Information can be passed to functions through
arguments. An argument is just like a variable.
Arguments are specified after the function name,
inside the parentheses. You can add as many arguments as you want, just
separate them with a comma.
<html>
<body>
<?php
function familyName($fname)
{
echo "$fname Refsnes.<br>";
}
familyName("Jani");
?>
</body>
</html>
The following example has a function with two
arguments ($fname and $year):
<html>
<body>
<?php
function familyName($fname, $year)
{
echo "$fname Refsnes. Born in $year
<br>";
}
familyName("Hege","1975");
?>
</body>
</html>
•Indexed or Numeric Arrays: An array with a
numeric index where values are stored linearly.
•Associative Arrays: An array with a string index
where instead of linear storage, each value can be assigned a specific key.
Passing indexed array as parameter
<html>
<body>
<?php
function ab($fruit)
{
echo”fruits list”;
foreach($fruit as $v)
{
echo $v;
}
}
$fruit=array(“apple”,”coconut”,”kiwi”);
ab($fruit);
?>
</body>
</html>
Passing associative array as an argument
<html>
<body>
$a=array(“color”=>”blue”,”number”=>3);
function ab($args)
{
extract($args);
echo $color;
echo $number;
}
ab($a);
?>
</body>
</html>
//call by reference program in php
<?php
function abc($x)
{
$x=$x-10;
return($x);
}
$a=50;
echo abc($a)."<br>";
echo ($a);
?>
Note: Call by reference: in the call by reference
method, instead of passing a value to the function being called a
reference/pointer to the original variable is passed.
Output
40
50
Retrieving parameters
func_get¬_args()-Returns an array of all
parameters provided to the function.
fun_get_arg()-returns a specific parameter of all
those provided to the function.
func_num_args()-returns the count of parameters
provided to the function
<?php
function fruits( )
{
echo “Number of Arguments passed:”.func_num_args();
if(func_num_args()==0)
{
return 0;
}
else
{
for($i=0,$i<fun_num_args();$i++)
{
echo “hello”.func_get_arg($i);
}
}
print_r(func_get_args());
}
fruits(“oranges”,”bananas”,”grapes”,”mangoes”);
?>
PHP Functions returning value
A function can return a value using the return
statement in conjunction with a value or object. return stops the execution of
the function and sends the value back to the calling code.
You can return more than one value from a
function using return array(1,2,3,4).
Following example takes two integer parameters
and add them together and then returns their sum to the calling program. Note
that return keyword is used to return a value from a function.
<?php
function addFunction($num1, $num2)
{
$sum = $num1 + $num2;
return $sum;
}
$return_value = addFunction(10, 20);
echo "Returned value from the function :
$return_value";
?>
PHP Variable Scope
There are three types of scopes in
PHP.
•Global Scope
•Local Scope
•Static Scope
PHP Global Scope
A variable declared in the main flow
of the code (not inside a function) has a global scope. These variables can't
be used inside functions.
<?php
$number = 10; // global scope
echo $number; // outputs 10
function num()
{
echo $number; // $number is undefined
here
}
?>
PHP Local Scope
A variable declared inside a function
has a local scope. This variable is unique to this function and can only be
accessed within the function. You can define different variables with the same
name in different functions.
<?php
function hello()
{
$txt = 'Hello World'; // local scope
echo $txt; // $txt can be used here
}
hello();
// $txt cannot be used outside
?>
PHP Global Variables in Local Scope
There are two ways to access global
variables within a function.
•Using the global keyword
•Using the $GLOBALS array
1. PHP global Keyword
You can use global keyword inside a
function to access global variables. Before using variables, add global keyword
followed by comma-separated variable names you need to use inside the function.
<?php
$x = 'Hyvor';
$y = 'Developer';
function websiteName()
{
global $x, $y;
echo $x, $y;
}
websiteName(); // outputs
HyvorDeveloper
?>
output- HyvorDeveloper
2. PHP $GLOBALS Array
PHP saves all the global variables in
PHP-defined $GLOBALS array. The array key contains the variable name. The array
value contains the variable value. The previous example can be written as
follows.
<?php
$x = 'Hyvor';
$y = 'Developer';
function websiteName()
{
echo $GLOBALS['x'], $GLOBALS['y'];
}
websiteName(); // outputs
HyvorDeveloper
?>
output:- HyvorDeveloper
PHP Static Scope
As we discussed earlier, local scope
variables are deleted after the end of the execution of the function. But,
sometimes we need to keep the variable alive.
<?php
function test()
{
static $number = 0; // declare static
variable
echo $number . '<br>'; // echo
number with line break
$number = $number + 5; // add five to
$number
}
test(); // 0
test(); // 5
test(); // 10
output:-
0
5
10
Anonymous functions
Anonymous
functions, also known as closures, allow the creation of functions which have
no specified name. They are most useful as the value of callback parameters,
but they have many other uses.
Anonymous
functions are implemented using the Closure class.
<?php
$greet
= function($name)
{
printf("Hello
%s\r\n", $name);
};
$greet('World');
$greet('PHP');
?>
PHP String
PHP
string is a sequence of characters i.e., used to store and manipulate text. PHP
supports only 256-character set and so that it does not offer native Unicode
support. There are 4 ways to specify a string literal in PHP.
•single
quoted
•double
quoted
•heredoc
syntax
•newdoc
syntax
Single Quoted
We
can create a string in PHP by enclosing the text in a single-quote. It is the
easiest way to specify string in PHP.
For
specifying a literal single quote, escape it with a backslash (\) and to
specify a literal backslash (\) use double backslash (\\). All the other
instances with backslash such as \r or \n, will be output same as they
specified instead of having any special meaning.
<?php
$str='Hello
text within single quote';
echo
$str;
?>
Double Quoted
In
PHP, we can specify string through enclosing text within double quote also. But
escape sequences and variables will be interpreted using double quote PHP
strings.
<?php
$str="Hello
text within double quote";
echo
$str;
?>
Heredoc
Heredoc
syntax (<<<) is the third way to delimit strings. In Heredoc syntax,
an identifier is provided after this heredoc <<< operator, and
immediately a new line is started to write any text. To close the quotation,
the string follows itself and then again that same identifier is provided. That
closing identifier must begin from the new line without any whitespace or tab.
Naming Rules
The
identifier should follow the naming rule that it must contain only alphanumeric
characters and underscor
<?php
$str
= <<<Demo Demo;
echo
$str;
?>
Newdoc
Newdoc
is similar to the heredoc, but in newdoc parsing is not done. It is also
identified with three less than symbols <<< followed by an identifier.
But here identifier is enclosed in single-quote, e.g. <<<'EXP'. Newdoc
follows the same rule as heredocs.
<?php
$str
= <<<'DEMO'
Welcome
to javaTpoint.
Learn
with newdoc example.
DEMO;
echo
$str;
echo
'</br>';
echo <<< 'Demo' // Here we are not storing string content
in variable str.
Welcome
to javaTpoint.
Learn
with newdoc example.
Demo;
?>
Printing Functions:-
PHP echo() Function
PHP
echo() function is important string function. It is used to display one or more
strings. In another words we can say that the echo() function outputs one or
more string.
<?php
$str
="Hello JavaTpoint";
echo
"By using 'echo()' function your string is :".$str;
?>
PHP print() Function
PHP
print() function is important function, which is used to output one or more
string.
<?php
$str
= "Hello PHP";
print
$str;
?>
PHP string printf() Function
PHP
string printf() function predefined functions. It is used to output a formatted
string. We can pass the arg1, arg2, arg++ parameters at percent (%) signs in
the main string
Syntax:
printf(format,arg1,arg2,arg++);
<?php
$number
= 12345;
printf("%f",$number);
?>
output:
12345.000000
The sprintf()
function is used to output a formatted string.
Syntax
sprintf(format,
arg1, arg2, arg++)
The
sprintf() function returns a formatted string.
The
following is an example −
Example
<?php
$val
= 299;
$txt
= sprintf("%f",$val);
echo
$txt;
?>
print_r() Function
The
print_r() function is a built-in function in PHP and is used to print or
display information stored in a variable.
<?php
$a
= array ('apple','banana’,’kiwi’);
print_r
($a);
?>
Output:-
Array([0]=>apple[1]=>banana[2]=>kiwi
var_dump
var_dump
— Dumps information about a variable
<?php
$a
= array ('apple','banana’,’kiwi’);
var_dump($a);
?>
Output:-
Array(3){([0]=>string(5)”apple”[1]=>string(6)”banana”[2]=>string(4)”kiwi”}
Escape
sequences are used for escaping a character during the string parsing. It is
also used for giving special meaning to represent line breaks, tabs, alert and
more.
•\’
– To escape ‘ within single quoted string.
•\”
– To escape “ within double quoted string.
•\\
– To escape the backslash.
•\$
– To escape $.
•\n
– To add line breaks between string.
•\t
– To add tab space.
•\r
– For carriage return.
<?php
$str
= "Is your name O'Reilly?";
echo
addslashes($str);
?>
//
Outputs: Is your name O\'Reilly?
How
do the PHP equality (== double equals) and identity (=== triple equals)
comparison operators differ?
Comparing
Strings
Equal
Operator == The comparison operator called Equal Operator is the double equal
sign “==”. This operator accepts two inputs to compare and returns true value
if both of the values are same (It compares only value of variable, not data
types) and return a false value if both of the values are not same.
<?php
//
Variable contains integer value
$x
= 999;
//
Vatiable contains string value
$y
= '999';
//
Compare $x and $y
if
($x == $y)
echo
'Same content';
else
echo
'Different content';
?>
Output:-
Same content
Identical
Operator ===
The
comparison operator called as the Identical operator is the triple equal sign
“===”. This operator allows for a much stricter comparison between the given
variables or values.
This
operator returns true if both variable contains same information and same data
types otherwise return false.
<?php
//
Variable contains integer value
$x
= 999;
//
Vatiable contains string value
$y
= '999';
//
Compare $x and $y
if
($x === $y)
echo
'Data type and value both are same';
else
echo
'Data type or value are different';
?>
Output:-Data
type or value are different
similar_text()
Function
The
similar_text() function is a built-in function in PHP. This function calculates
the similarity of two strings and returns the number of matching characters in
the two strings. The function operates by finding the longest first common
sub-string, and repeating this for the prefixes and the suffixes, recursively.
The sum of lengths of all the common sub-strings is returned.
It
can also calculate the similarity of the two strings in percent. The function
calculates the similarity in percent, by dividing the result by the average of
the lengths of the given strings times 100.
Syntax
:
similar_text(
$string1, $string2, $percent)
Parameters:
This function accepts three parameters as shown in the above syntax out of
which first two must be supplied and last one is optional. All of these
parameters are described below:
•$string1,
$string2 : These mandatory parameters specify the two strings to be compared
•$percent
: This parameter is optional. It specifies a variable name for storing the
similarity in percent. By passing a reference as third argument, the function
will calculate the
<?php
$sim
= similar_text("hackers", "hackathons", $percent);
//
To display the number of matching characters
echo
"Number of similar characters : $sim\n";
//
To display the percentage of matching characters
echo
"Percentage of similar characters : $percent\n";
?>
Output:-Number
of similar characters : 5
Percentage
of similar characters : 58
levenshtein()
Function
The
levenshtein() function is an inbuilt function in PHP. The levenshtein()
function is used to calculate the levenshtein distance between two strings. The
Levenshtein distance between two strings is defined as the minimum number of
characters needed to insert, delete or replace in a given string $string1 to
transform it to a string $string2.
Syntax:int
levenshtein($str1, $str2)
Parameters:
The levenshtein() function accepts two parameters, both of the parameters are
compulsory:
1.$str1:
This is a required parameter which specifies the string to be transformed to
another.
2.$str2:
This is also a required parameter which specifies the string in which the first
string($str1) needed to be trasformed.
Return
Value: The levenshtein() function returns an integral value which is the
levenshtein distance otherwise -1, if one of the arguments exceeds the limit of
255 characters.
<?php
//
PHP code to find levenshtein distance
//
between $str1 and $str2
$str1
= 'abc';
$str2
= 'aef';
print_r(levenshtein($str1,
$str2));
?>
Output:
2
Concatenation
of two strings in PHP
There
are two string operators. The first is the concatenation operator (‘.‘), which
returns the concatenation of its right and left arguments. The second is the
concatenating assignment operator (‘.=‘), which appends the argument on the
right side to the argument on the left side.
<?php
//
First String
$a
= 'Hello';
//
Second String
$b
= 'World!';
//
Concatenation Of String
$c
= $a.$b;
//
print Concatenate String
echo
" $c \n";
?>
Output
: HelloWorld!
String
function
strlen()
function
The
strlen() function returns length of the string.
Syntax
int
strlen ( string $string )
Example
<?php
$str="my
name is Sonoo jaiswal";
$str=strlen($str);
echo
$str;
?>
Output:24
PHP
strrev() function
The
strrev() function returns reversed string.
Syntax
1.string
strrev ( string $string )
Example
<?php
$str="my
name is Sonoo jaiswal";
$str=strrev($str);
echo
$str;
?>
Output:lawsiaj
oonoS si eman ym
PHP
ucwords() function
The
ucwords() function returns string converting first character of each word into
uppercase.
Syntax:-string
ucwords ( string $str )
Example
<?php
$str="my
name is Sonoo jaiswal";
$str=ucwords($str);
echo
$str;
?>
Output:My
Name Is Sonoo Jaiswal
PHP
lcfirst() function
The
lcfirst() function returns string converting first character into lowercase. It
doesn't change the case of other characters.
Syntax
string
lcfirst ( string $str )
Example
<?php
$str="MY
name IS KHAN";
$str=lcfirst($str);
echo
$str;
?>
Output:mY
name IS KHAN
PHP
ucfirst() function
The
ucfirst() function returns string converting first character into uppercase. It
doesn't change the case of other characters.
Syntax
string
ucfirst ( string $str )
Example
<?php
$str="my
name is KHAN";
$str=ucfirst($str);
echo
$str;
?>
Output:My
name is KHAN
PHP
strtoupper() function
The
strtoupper() function returns string in uppercase letter.
Syntax
string
strtoupper ( string $string )
Example
<?php
$str="My
name is KHAN";
$str=strtoupper($str);
echo
$str;
?>
Output:-MY
NAME IS KHAN
strtolower()
function
The
strtolower() function returns string in lowercase letter.
Syntax
string
strtolower ( string $string )
Example
<?php
$str="My
name is KHAN";
$str=strtolower($str);
echo
$str;
?>
Output:-my
name is khan