PHP VI TH 3rd
PHP VI TH 3rd
Reusability: If we have a common code that we would like to use at various parts of a
program, we can simply contain it within a function and call it whenever required.
This reduces the time and effort of repetition of a single code. This can be done both
within a program and also by importing the PHP file, containing the function, in some
other program
Easier error detection: Since, our code is divided into functions, we can easily detect
in which function, the error could lie and fix them fast and easily.
Easily maintained: As we have used functions in our program, so if anything or any
line of code needs to be changed, we can easily change it inside the function and the
change will be reflected everywhere, where the function is called. Hence, easy to
maintain.wherever necessary by simply calling it.
Syntax:
function function_name()
{
//code
}
Syntax
Function function_name(Para1,para2,......)
<?php
<?php
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:
// pass by value
function val($num) {
$num += 2;
return $num;
}
// pass by reference
function ref(&$num) {
$num += 10;
return $num;
}
$n = 10;
val($n);
echo "The original value is still $n \n";
ref($n);
echo "The original value changes to $n";
?>
Sometimes the term argument is used for parameter. Actually, the two terms have a certain
difference.
Recursion:- PHP also supports recursive function call like C/C++. In such case, we call
current function within function. It is also known as recursion.
Example:
1. <?php
2. function display($number) {
3. if($number<=5){
4. echo "$number <br/>";
5. display($number+1);
6. }
7. }
8. display(1);
9. ?>
1)Checkdate():
<?php
var_dump(checkdate(12,31,-400));
echo "<br>";
var_dump(checkdate(2,29,2003));
echo "<br>";
var_dump(checkdate(2,29,2004));
?>
Example:
<?php
$date=date_create("2013-03-15");
date_add($date,date_interval_create_from_date_string("40 days"));
echo date_format($date,"Y-m-d");
?>
Syntax:date_interval_create_from_date_string(datetime)
Example:
<?php
$date = date_create('2019-01-01');
date_add($date, date_interval_create_from_date_string('1 year 35 days'));
echo date_format($date, 'Y-m-d');
?>
Syntax:gettimeofday(return_float)
Example:
<?php
// Print the array from gettimeofday()
print_r(gettimeofday());
echo "<br><br>";
Syntax:strtotime(time, now);
Example:
<?php
echo(strtotime("now") . "<br>");
echo(strtotime("3 October 2005") . "<br>");
echo(strtotime("+5 hours") . "<br>");
echo(strtotime("+1 week") . "<br>");
echo(strtotime("+1 week 3 days 7 hours 5 seconds") . "<br>");
echo(strtotime("next Monday") . "<br>");
echo(strtotime("last Sunday"));
?>
Syntax:time()
Example:
<?php
$t=time();
echo($t . "<br>");
echo(date("Y-m-d",$t));
?>
<?php
print_r(localtime());
echo "<br><br>";
print_r(localtime(time(),true));
?>
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.
1. single quoted
2. double quoted
3. heredoc syntax
1)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.
Example 1:
<?php
$str='Hello text within single quote';
echo $str;
?>
Example 2:
<?php
$str1='Hello text
multiple line
text within single quoted string';
$str2='Using double "quote" directly inside single quoted string';
$str3='Using escape sequences \n in single quoted string';
echo "$str1 <br/> $str2 <br/> $str3";
?>
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.
Example:
<?php
$str="Hello text within double quote";
echo $str;
?>
3)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 underscores, and must start with an underscore or a non-digit character.
Example 1:
<?php
$str = <<<Demo
It is a valid example
Demo; //Valid code as whitespace or tab is not valid before closing identifier
echo $str;
?>
Example 2:
<?php
$str = <<<Demo
It is Invalid example
Demo; //Invalid code as whitespace or tab is not valid before closing identifier
echo $str;
?>
<?php
$str = <<<'DEMO'
Welcome .
Learn with newdoc example.
DEMO;
echo $str;
echo '</br>';
echo <<< 'Demo' // Here we are not storing string content in variable str.
Welcome
Learn with newdoc example.
Demo;
?>
String Functions:
The addcslashes() function returns a string with backslashes in front of the specified
characters.The addcslashes() function is case-sensitive.Be careful using addcslashes() on 0
(NULL), r (carriage return), n (newline), f (form feed), t (tab) and v (vertical tab). In PHP, \0,
\r, \n, \t, \f and \v are predefined escape sequences.
Syntax
addcslashes(string,characters)
<?php
$str = "Welcome to my Homepage!";
echo $str."<br>";
echo addcslashes($str,'m')."<br>";
echo addcslashes($str,'H')."<br>";
?>
<?php
$str = "Hello World!\n\n";
echo $str;
echo chop($str);
?>
The chunk_split() function splits a string into a series of smaller parts. This function
does not alter the original string.
Syntax
chunk_split(string,length,end)
Example:
<?php
$str = "Hello world!";
echo chunk_split($str,1,".");
?>
Syntax
convert_uudecode(string)
<?php
$str = ",2&5L;&\@=V]R;&0A `";
echo convert_uudecode($str);
?>
Syntax:
convert_uuencode(string)
<?php
$str = "Hello world!";
echo convert_uuencode($str);
?>
The str_ireplace() function replaces some characters with some other characters in a
string.
Syntax
str_ireplace(find,replace,string,count)
<?php
echo str_ireplace("WORLD","Peter","Hello world!");
?>
Syntax:
str_split(string,length)
Syntax:
<?php
$var1="Hello PHP";
echo "Your Number is:".$var1;
echo "<br>";
echo "By using 'strrev()' function:".strrev("$var1");
?>
9) PHP explode() function
PHP explode() is a string function, which splits a string by a string. In simple words,
we can say that it breaks a string into an array. The explode() function has a "separator"
parameter, which cannot contain an empty string, because it holds the original string that is to
be split. It is a binary-safe function.
The explode() function returns an array of strings created by splitting the original string.
Syntax:
Parameters
There are three parameters passed in the explode() function, in which two parameters
are mandatory, and the last one is optional to pass. These parameters are as follows:
$separator:
This parameter specifies the character for the point at which the original string will split.
In simple words, we can say that whenever this character is found in the string, the string will
be divided into parts.
$originalString: This parameter holds the string which is to be split into array.
<?php
// original string
$Original_str = "Hello, we are here to help you.";
// Passed zero
print_r (explode (" ",$Original_str, 0));
// Passed positive value
print_r (explode (" ",$Original_str, 4));
// Passed negative value
print_r (explode (" ",$Original_str, -3));
?>
10) PHP string Implode() Function
PHP implode() is a string function, which joins the array elements in a string. It is
a binary-safe function. In implode() function, parameters can be passed in any order.
The implode() function works same as the join() function and returns a string created from
the elements of the array. Basically, this function joins all elements of array in one string.
Syntax
There are two syntax are available for implode() function, which are given below:
Parameters
There are two parameters can be passed in the implode() function, one of which is
mandatory, and another one is optional. These parameters are as follows:
$glue (optional):
1. It is an optional and string type of parameter. It contains the value to join the array
elements and form a string. Basically, $glue is used to join the string.
$pieces (mandatory):
This parameter contains the array of string to implode. The array elements are mandatory
to pass in implode() function to join into one string.
<?php
echo "Before using 'implode()' function: <br>";
echo "array('Welcome', 'to', 'PHP', 'tutorial') <br> <br>";
//store array element in a variable
$arr = array('Welcome', 'to', 'PHP', 'tutorial');
//join array elements in a string by + operator
echo "After using 'implode()' function: <br>";
echo implode("+",$arr);
?>