UNIT2 php
UNIT2 php
UNIT-2
1
PHP Functions
PHP function is a piece of code that can be reused many times. It can take input as argument list
and return value.
A function is a piece of code that takes another input in the form of a parameter, processes it,
and then returns a value. A PHP Function feature is a piece of code that can be used over and
over again and accepts argument lists as input, and returns a value.
There are two types of functions in PHP i.e. Built-in and User-defined functions. These functions
are used in the program to perform various tasks. In PHP, a huge number of functions are defined
and can be used anywhere in the program. Though it has a lot of advantages of not writing the
code again and again and the functions come with the package itself, it is easy for the developer
to use the built-in functions. But all the built-in functions have a predefined meaning and perform
a specific task itself. So the developer started developing user-defined functions where the
developer can write the specific task code inside any function and can be used anywhere in the
program. The user-defined functions are called in the program in a class or in a method of a
program to perform the task based on applications requirement.
➢ 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.
Less Code: It saves a lot of code because you don't need to write the logic many times. By the
use of function, you can write the logic only once and reuse it.
Easy to understand: PHP functions separate the programming logic. So it is easier to understand
the flow of the application because every logic is divided in the form of functions.
Creating a Function
While creating a user defined function we need to keep few things in mind:
Syntax:
function function_name(){
executable code;
1. <?php
Output
2. function sayHello(){
3. echo "Hello PHP Function"; Hello PHP Function
4. }
5. sayHello();//calling function
6. ?>
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:
executable code;
Example
<?php
proGeek(2, 3, 5);
?>
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
defGeek("Ram", 15);
// In this call, the default value 12
// will be considered
defGeek("Adam");
?>
It is possible to pass arguments to functions by reference. This means that a reference to the
variable is manipulated by the function rather than a copy of the variable's value. Any changes
made to an argument in these cases will change the value of the original variable. We can pass
an argument by reference by adding an ampersand to the variable name in either the function
call or the function definition.
<html><head>
function addFive($num) {
$num += 5;
PHP NOTES FOR MGSU EXAMS GORISH MITTAL
5
function addSix(&$num) {
$num += 6;
$orignum = 10;
addFive( $orignum );
addSix( $orignum );
?>
</body>
</html>
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
// function along with three parameters The product is 30
function proGeek($num1, $num2, $num3)
?>
<?php
function add(...$numbers) {
Output
$sum = 0;
return $sum;
?>
• local
• global
• static
A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside
a function:
EXAMPLE
<?php
$x = 5; // global scope
Output
function myTest() {
Variable x inside function is:
// using x inside this function will generate an error
Variable x outside function is: 5
echo "<p>Variable x inside function is: $x</p>";
myTest();
?>
A variable declared within a function has a LOCAL SCOPE and can only be accessed within that
function
<?php
function myTest() {
Output
$x = 5; // local scope
Variable x inside function is: 5
echo "<p>Variable x inside function is: $x</p>"; Variable x outside function is:
}
myTest();
?>
You can have local variables with the same name in different functions, because local variables
are only recognized by the function in which they are declared
sometimes we want a local variable NOT to be deleted. We need it for a further job.
To do this, use the static keyword when you first declare the variable:
Example
<?php
Output
function myTest() {
0
static $x = 0;
1
echo $x;
2
$x++;
myTest();
myTest();
myTest();
?>
Then, each time the function is called, that variable will still have the information it contained
----------------------------------------------------------
The global keyword is used to access a global variable from within a function.
To do this, use the global keyword before the variables (inside the function):
Example
<?php
$x = 5;
$y = 10;
function myTest() {
$y = $x + $y;
myTest();
PHP Arrays
Arrays in PHP is a type of data structure that allows us to store multiple elements of similar data
type under a single variable thereby saving us the effort of creating a different variable for every
data. The arrays are helpful to create a list of elements of similar types, which can be accessed
using their index or key. Suppose we want to store five names and print them accordingly. This
can be easily done by the use of five different string variables. But if instead of five, the number
rises to a hundred, then it would be really difficult for the user or developer to create so many
different variables. Here array comes into play and helps us to store every element within a single
variable and also allows easy access using an index or a key. An array is created using an array()
function in PHP.
Easy to traverse: By the help of single loop, we can traverse all the elements of an array.
• 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.
• Multidimensional Arrays: An array which contains single or multiple array within it and
can be accessed via multiple indices.
These type of arrays can be used to store any type of elements, but an index is always a number.
By default, the index starts at zero. These arrays can be created in two different ways as shown in
the following example:
<?php
?>
Associative Arrays
These types of arrays are similar to the indexed arrays but instead of linear storage, every value
can be assigned with a user-defined key of string type.
<?php
"Ram"=>"Rani", "Salim"=>"Sara",
"Raghav"=>"Ravina");
?>
Multidimensional Arrays
Multi-dimensional arrays are such arrays that store another array at each index instead of a
single element. In other words, we can define multi-dimensional arrays as an array of arrays. As
the name suggests, every element in this array can be an array and they can also hold other
sub-arrays within. Arrays or sub-arrays in multidimensional arrays can be accessed using
multiple dimensions.
Example:
<?php
// Defining a multidimensional array
$favorites = array(
array(
"name" => "Dave Punk",
"mob" => "5689741523",
Output
"email" => "[email protected]",
),
array( Dave Punk email-id is:
"name" => "Monty Smith", [email protected]
"mob" => "2584369721", John Flinch mobile number is:
"email" => "[email protected]", 9875147536
),
array(
"name" => "John Flinch",
"mob" => "9875147536",
"email" => "[email protected]",
)
);
// Accessing elements
echo "Dave Punk email-id is: " . $favorites[0]["email"], "\n";
echo "John Flinch mobile number is: " . $favorites[2]["mob"];
?>
PHP array() function creates and returns an array. It allows you to create indexed, associative and
multidimensional arrays.
Syntax
Example
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
4. ?>
Output
Season are: summer, winter, spring and autumn
Syntax
Example
1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
3. print_r(array_change_key_case($salary,CASE_UPPER)); ?>
PHP NOTES FOR MGSU EXAMS GORISH MITTAL
15
Output
Array ( [SONOO] => 550000 [VIMAL] => 250000 [RATAN] => 200000 )
Syntax
Example
Output
1. <?php
4
2. $season=array("summer","winter","spring","autumn");
3. echo count($season);
4. ?>
Syntax
Example Output
autumn
spring
1. <?php
summer
2. $season=array("summer","winter","spring","autumn"); winter
3. sort($season);
4. foreach( $season as $s )
5. {
Syntax
Example
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. $reverseseason=array_reverse($season); Output
autumn
4. foreach( $reverseseason as $s ) spring
5. { winter
6. echo "$s<br />"; summer
7. }
8. ?>
PHP array_search() function searches the specified value in an array. It returns key if search is
successful.
Syntax
Example
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. $key=array_search("spring",$season);
4. echo $key; Output
5. ?> 2
PHP array_intersect() function returns the intersection of two array. In other words, it returns the
matching elements of two array.
Syntax
Example
1. <?php
2. $name1=array("sonoo","john","vivek","smith");
3. $name2=array("umesh","sonoo","kartik","smith");
4. $name3=array_intersect($name1,$name2); Output
5. foreach( $name3 as $n )
sonoo
6. { smith
7. echo "$n<br />";
8. }
9. ?>
PHP array_chunk() function splits array into chunks. By using array_chunk() method, you can divide
array into many parts.
Syntax
Example
1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
3. print_r(array_chunk($salary,2));
4. ?>
Output
Array (
[0] => Array ( [0] => 550000 [1] => 250000 )
[1] => Array ( [0] => 200000 )
)
-------------------------------------------------------------------------------
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. Strings can be seen as a stream of characters. For example, ‘G’ is a character
and ‘GeeksforGeeks’ is a string.
1. single quoted
2. double quoted
3. heredoc syntax
4. newdoc syntax (since PHP 5.3)
Single Quoted
PHP NOTES FOR MGSU EXAMS GORISH MITTAL
19
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.
This type of string does not process special characters inside quotes.
1. <?php
Output
2. $str='Hello text within single quote';
3. echo $str; Hello text within single quote
4. ?>
If the single quote is part of the string value, it can be escaped using the backslash.The
code below illustrates how to escape a single quote.
Example 2
1. <?php
2. $str1='Hello text
3. multiple line
4. text within single quoted string';
5. $str2='Using double "quote" directly inside single quoted string';
6. $str3='Using escape sequences \n in single quoted string';
7. echo "$str1 <br/> $str2 <br/> $str3";
8.
9. echo 'I \'ll be back after 20 minutes';
10.
Output
11. ?>
Hello text multiple line text within single quoted string
Using double "quote" directly inside single quoted string
Using escape sequences \n in single quoted string
I'll be back after 20 minutes
Double Quoted
In PHP, we can specify string through enclosing text within double quote also
you can't use double quote directly inside double quoted string.
Variable names can be used inside double quotes and their values will be displayed.
1. <?php
2. $str="Hello text within double quote"; Output
3. echo $str;
4. ?> Hello text within double quote
1. <?php
2. $str1="Using double "quote" directly inside double quoted string";
3. echo $str1;
4. ?>
Output
Parse error: syntax error, unexpected 'quote' (T_STRING) in
C:\wamp\www\string1.php on line 2
1. <?php
2. $num1=10;
3. echo "Number is: $num1";
4. ?>
Output
Number is: 10
https://www.youtube.com/watch?v=wcKf9XCFupo
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.
For Example
Valid Example
Output
1. <?php
It is a valid example
2. $str = <<<Demo
3. It is a valid example
4. Demo; //Valid code as whitespace or tab is not valid before closing identifier
5. echo $str;
6. ?>
Invalid Example
We cannot use any whitespace or tab before and after the identifier and semicolon, which means
identifier must not be indented. The identifier must begin from the new line.
1. <?php
2. $str = <<<Demo
3. It is Invalid example
4. Demo; //Invalid code as whitespace or tab is not valid before closing identifier
5. echo $str;
6. ?>
‘
Output
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.
The difference between newdoc and heredoc is that - Newdoc is a single-quoted string whereas
heredoc is a double-quoted string.
Example-1:
1. <?php
2. $str = <<<'DEMO'
3. Welcome to javaTpoint.
4. Learn with newdoc example.
5. DEMO;
6. echo $str;
7. echo '</br>';
8.
9. echo <<< 'Demo' // Here we are not storing string content in variable str.
PHP NOTES FOR MGSU EXAMS GORISH MITTAL
23
Output
PHP scripts.
PHP has a predefined function to get the length of a string. Strlen() displays the length of any
string. It is more commonly used in validating input fields where the user is limited to enter a
Syntax
Strlen(string);
Output
20
Example
<?php
?>
Another function which enables display of the number of words in any specific string is
Syntax
Output
Str_word_count(string)
Example 3
<?php
?>
3. Reversing a String
Strrev() is used for reversing a string. You can use this function to get the reverse version of any
string.
Syntax Output
Strev(string)
syawduolC ot emocleW
Example
<?php
echo strrev(“Welcome to Cloudways”);// will return the string starting from the end
?>
Strpos() enables searching particular text within a string. It works simply by matching the
specific text in a string. If found, then it returns the specific position. If not found at all, then it
will return “False”. Strops() is most commonly used in validating input fields like email.
Syntax
Output
Strpos(string,text);
Example 11
<?php
?>
Str_replace() is a built-in function, basically used for replacing specific text within a string.
Syntax
Str_replace(string to be replaced,text,string)
Example
Welcome to the programming world
<?php
?>
Syntax
Ucwords(string)
Output
Example
Welcome To The Php World
<?php
?>
Syntax
Output
Strtoupper(string);
<?php
echo strtoupper(“welcome to cloudways”);// It will convert all letters of string into uppercase
?>
Syntax
Strtolower(string)
Example
<?php
Output
echo strtolower(“WELCOME TO CLOUDWAYS”);
welcome to cloudways
?>
9. Repeating a String
PHP provides a built-in function for repeating a string a specific number of times.
Syntax
Str_repeat(string,repeat)
Output
Example
<?php =============
echo str_repeat(“=”,13);
?>
Trim() is dedicated to remove white spaces and predefined characters from a both the sides of a
string.
Syntax
Output
trim(string,charlist)
<?php
echo trim(“$str”,”Wording”);
?>
PHP date() Function: The PHP date() function converts timestamp to a more readable date and time
format.
The computer stores dates and times in a format called UNIX Timestamp, which measures time as a
number of seconds since the beginning of the Unix epoch (midnight Greenwich Mean Time on January
1, 1970, i.e. January 1, 1970, 00:00:00 GMT ). Since this is an impractical format for humans to read, PHP
converts timestamp to a format that is readable and more understandable to humans.
Syntax:
date(format, timestamp)
Explanation:
• The format parameter in the date() function specifies the format of returned date and time.
• The timestamp is an optional parameter, if it is not included then the current date and time will
be used.
Example: The below program explains the usage of the date() function in PHP.
<?php
echo "Today's date is :";
$today = date("d/m/Y");
echo $today;
?>
Output
Formatting options available in date() function: The format parameter of the date() function is
a string that can contain multiple characters allowing to generate the dates in various formats.
Date-related formatting characters that are commonly used in the format string:
➢ d: Represents day of the month; two digits with leading zeros (01 or 31).
➢ D: Represents day of the week in the text as an abbreviation (Mon to Sun).
➢ m: Represents month in numbers with leading zeros (01 or 12).
➢ M: Represents month in text, abbreviated (Jan to Dec).
➢ y: Represents year in two digits (08 or 14).
➢ Y: Represents year in four digits (2008 or 2014).
The parts of the date can be separated by inserting other characters, like hyphens (-), dots (.), slashes (/),
or spaces to add additional visual formatting.
Example: The below example explains the usage of the date() function in PHP.
<?php
Output
echo "Today's date in various formats:" . "\n";
Today's date in various formats:
echo date("d/m/Y") . "\n";
05/12/2017
echo date("d-m-Y") . "\n";
05-12-2017
echo date("d.m.Y") . "\n";
05.12.2017
echo date("d.M.Y/D");
05.Dec.2017/Tue
?>
PHP time() Function: The time() function is used to get the current time as a Unix timestamp (the
number of seconds since the beginning of the Unix epoch: January 1, 1970, 00:00:00 GMT).
Example: The below example explains the usage of the time() function in PHP.
<?php
Output
$timestamp = time();
1512486297
echo($timestamp);
December 05, 2017 03:04:57 PM
echo "\n";
echo(date("F d, Y h:i:s A", $timestamp));
?>
PHP mktime() Function: The mktime() function is used to create the timestamp for a specific date
and time. If no date and time are provided, the timestamp for the current date and time is returned.
Syntax:
mktime(hour, minute, second, month, day, year)
Example: The below example explains the usage of the mktime() function in PHP.
<?php Output
echo mktime(23, 21, 50, 11, 25, 2017);
1511652110
?>