Unit 1 (BCA 2)
Unit 1 (BCA 2)
What is PHP:
Page | 1
What You Can Do with PHP
PHP Features
PHP is very popular language because of its simplicity and open source. There are some
important features of PHP given below:
Page | 2
Performance:
PHP script is executed much faster than those scripts which are written in other
languages such as JSP and ASP.
PHP uses its own memory, so the server workload and loading time is automatically
reduced, which results in faster processing speed and better performance.
Open Source:
PHP source code and software are freely available on the web.
You can develop all the versions of PHP according to your requirement without paying
any cost. All its components are free to download and use.
PHP has easily understandable syntax. Programmers are comfortable coding with it.
Embedded:
PHP code can be easily embedded within HTML tags and script.
Platform Independent:
PHP is available for WINDOWS, MAC, LINUX & UNIX operating system. A PHP application
developed in one OS can be easily executed in other OS also.
Database Support:
PHP supports all the leading databases such as MySQL, SQLite, ODBC, etc.
Error Reporting -
PHP has predefined error reporting constants to generate an error notice or warning at
runtime. E.g., E_ERROR, E_WARNING, E_STRICT, E_PARSE.
PHP allows us to use a variable without declaring its datatype. It will be taken automatically
at the time of execution based on the type of data it contains on its value.
PHP is compatible with almost all local servers used today like Apache, Netscape, Microsoft
IIS, etc.
Security:
PHP is a secure language to develop the website. It consists of multiple layers of security to
prevent threads and malicious attacks.
Control:
Different programming languages require long script or code, whereas PHP can do the
same work in a few lines of code.
Page | 3
It has maximum control over the websites like you can make changes easily whenever
you want.
Disadvantages of PHP
Despite the advantages of the PHP Hypertext Pre processor, the scripting language also has
some disadvantages. Some of the disadvantages are explained below.
Security : Since it is open sourced, so all people can see the source code, if there are
bugs in the source code, it can be used by people to explore the weakness of PHP
Not suitable for large applications: PHP is not highly modular, huge applications
created out of the programming language will be difficult to maintain.
Weak type: Implicit conversion may surprise unwary programmers and lead to
unexpected bugs. For example, the strings “1000” and “1e3” compare equal because
they are implicitly cast to floating point numbers.
MySQL:
MySQL is an open-source database so you don't have to pay a single penny to use it.
MySQL is a very powerful program so it can handle a large set of functionality of the
most expensive and powerful database packages.
MySQL is customizable because it is an open source database and the open-source GPL
license facilitates programmers to modify the SQL software according to their own
specific environment.
MySQL is quicker than other databases so it can work well even with the large data set.
MySQL supports many operating systems with many languages like PHP, PERL, C,
C++, JAVA, etc.
MySQL uses a standard form of the well-known SQL data language.
MySQL is very friendly with PHP, the most popular language for web development.
MySQL supports large databases, up to 50 million rows or more in a table. The default
file size limit for a table is 4GB, but you can increase this (if your operating system can
handle it) to a theoretical limit of 8 million terabytes (TB).
Page | 4
MySQL Features
MySQL version less than 5.0 doesn't support ROLE, COMMIT and stored procedure.
MySQL does not support a very large database size as efficiently.
MySQL doesn't handle transactions very efficiently and it is prone to data corruption.
MySQL is accused that it doesn't have a good developing and debugging tool compared
to paid databases.
MySQL doesn't support SQL check constraints.
PHP Syntax:
Page | 5
PHP Syntax
<?php
// your code here
?>
Ex:
<?php
echo "Hello, world!";
?>
PHP files are plain text files with .php extension. Inside a html file you can place php script.
Example: first.php
<!DOCTYPE>
<html>
<head>
<title>my first php program</title>
</head>
<body>
<?php
echo "welcome to computer cluster";
?>
</body>
</html
Execution:
Step1:
Open Mycomputer C drive xampp htdocs create your folder save your
fitst.php file
Ex: C:\xampp\htdocs\mahesh\first.php
Step2:
Page | 6
Step3:
Type localhost on your browser and press enter:
It will show the following:
Step5:
Now type the following on browser:
localhost/your folder name/
EX: localhost/Mahesh
Step6
Click on “first.php” and it will show the following:
Page | 7
PHP Comments:
Types:
echo Statement:
ex: <?php
print "welcome to computer cluster";
?>
Ex:<?php
$fname = "mahesh";
$lname = "babu";
print "My name is: $fname”;
print “$lname”;
?>
Page | 8
Ex: <?php
$fname = "mahesh";
$lname = "babu";
print"My name is: ".$fname,$lname;
?>
PHP Case Sensitivity
In PHP, keywords (e.g., echo, if, else, while), functions, user-defined functions, classes
are not case-sensitive.
However, all variable names are case-sensitive.
In the below example, you can see that all three echo statements are equal and valid:
Ex:
<!DOCTYPE html>
<html>
<body>
<?php
echo "Hello world using echo <br>";
ECHO "Hello world using ECHO <br>";
EcHo "Hello world using EcHo <br>";
?>
</body>
</html>
Ex: <!DOCTYPE html>
<html>
<body>
<?php
$color = "red";
echo "My car is " . $color . "<br>";
echo "My house is " . $COLOR . "<br>";
echo "My boat is " . $coLOR . "<br>";
?>
</body>
</html>
Page | 9
Ex:
<!DOCTYPE html>
<html>
<head>
<title>A Simple PHP File</title>
</head>
<body>
<h1>
<?php
echo "Hello, world!"; ?>
</h1>
</body>
</html>
Variables
Data Types
Constants
Operators
PHP Variables
Variables are used to store data, like string of text, numbers, etc.
A variable is a temporary storage that is used to store data temporarily.
In PHP, a variable is declared using $ sign followed by variable name.
Syntax
$variablename=value;
Page | 10
$y=44.6;
echo "string is: $str <br/>";
echo "integer is: $x <br/>";
echo "float is: $y <br/>";
?>
PHP Variable: Sum of two variables
File: variable2.php
<?php
$x=5;
$y=6;
$z=$x+$y;
echo $z;
?>
local
global
static
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.
ex: <?php
function localvar()
{
$num = 45; //local variable
echo "Local variable declared inside the function is: ". $num;
}
localvar();
?>
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.
Page | 11
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.
Ex: <?php
$name = "Lakshmi"; //Global Variable
function globalvar()
{
global $name;
echo "Variable inside the function: ". $name;
echo "</br>";
}
globalvar();
echo "Variable outside the function: ". $name;
?>
Static variable
Ex:
<?php
function staticvar()
{
static $num1 = 3; //static variable
$num2 = 6; //Non-static variable
//increment in non-static variable
$num1++;
//increment in static variable
$num2++;
The $var (single dollar) is a normal variable with the name var that stores any
value like string, integer, float, etc.
The $$var (double dollar) is a reference variable that stores the value of the
$variable inside it.
Page | 12
Ex:
<?php
$x = "abc";
$$x = 200;
echo $x."<br>;
echo $$x."<br>";
echo $abc;
?>
PHP data types are used to hold different types of data or values. PHP supports 8 primitive
data types that can be categorized further in 3 types:
Scalar Types:It holds only single value. There are 4 scalar data types in PHP.
1. boolean
2. integer
3. float
4. string
Compound Types
It can hold multiple values. There are 2 compound data types in PHP.
1. array
2. object
Special Types
1. resource
2. NULL
Boolean
Booleans are the simplest data type works like switch. It holds only two values: TRUE
(1) or FALSE (0).
Page | 13
It is often used with conditional statements.
If the condition is correct, it returns TRUE otherwise FALSE.
Example:
<?php
if (TRUE)
echo "This condition is TRUE.";
if (FALSE)
echo "This condition is FALSE.";
?>
Integer
Example:
<?php
$a = 115;
$b = -109;
echo "The positive number: ".$a;
echo "The negative number:".$b;
?>
Float
Ex: <?php
$n1 = 19.34;
$n2 = 54.472;
?>
Page | 14
PHP String
A string is a non-numeric data type. It holds letters or any alphabets, numbers, and
even special characters.
String values must be enclosed either within single quotes or in double quotes.
Ex:
<?php
$college= "shri gnanambica degree college";
echo "Hello $college";
>?
Array
An array is a compound data type. It can store multiple values of same data type in a
single variable.
Ex:
<?php
$bikes = array ("Royal Enfield", "Yamaha", "KTM");
echo "Array Element1: $bikes[0] <br>";
echo "Array Element2: $bikes[1] <br>";
echo "Array Element3: $bikes[2] <br>";
?>
object
Objects are the instances of user-defined classes that can store both values and
functions.
They must be explicitly declared.
Page | 15
PHP Resource
Resources are not the exact data type in PHP. Basically, these are used to store some function
calls or references to external PHP resources. For example - a database call. It is an external
resource.
PHP Null
Null is a special data type that has only one value: NULL.
The special type of data type NULL defined a variable with no value.
Ex: <?php
$nl = NULL;
echo $nl;
?>
Constants:
PHP constants follow the same PHP variable rules. For example, it can be started with letter
or underscore only.
define() :
define(name, value, case-insensitive)
name: specifies the constant name
value: specifies the constant value
case-insensitive: Default value is false. It means it is case sensitive by default.
Ex1:
<?php
define("MESSAGE","welcome to PHP");
echo MESSAGE;
?>
Ex2: <?php
echo MESSAGE;
Page | 16
echo message;
?>
Ex3: <?php
define("MESSAGE","Hello welcome to PHP",false);//case sensitive
echo MESSAGE;
echo message; ?>
The const keyword defines constants at compile time. It is a language construct not a
function.
It is bit faster than define().
It is always case sensitive.
Ex:<?php
const MESSAGE="Hello welcome to PHP";
echo MESSAGE;
?>
PHP Operators and Expressions:
In the above example, + is the binary + operator, 10 and 20 are operands and $num is
variable.
Arithmetic Operators
Assignment Operators
Comparison Operators
Incrementing/Decrementing Operators
Logical Operators
String Operators
Array Operators
Conditional Operator
Page | 17
Operator Description Example Result
+ Addition $x + $y Sum of $x and $y
- Subtraction $x - $y Difference of $x and $y.
* Multiplication $x * $y Product of $x and $y.
/ Division $x / $y Quotient of $x and $y
% Modulus $x % $y Remainder of $x divided by $y
** Exponentiation $x**$y Power of $x
Comparison Operators :
The comparison operators are used to compare two values in a Boolean fashion.
Page | 18
Logical Operators
The logical operators are typically used to combine conditional statements.
Operator Name Example Result
&& And $x && $y True if both $x and $y are true
|| Or $x || $y True if either $x or $y is true
! Not !$x True if $x is not true
String Operators
There are two operators which are specifically designed for strings.
Operator Description Example Result
. Concatenation $str1 . $str2 Concatenation of $str1 and $str2
.= Concatenation assignment $str1 .= $str2 Appends the $str2 to the $str1
Array Operators
The array operators are used to compare arrays:
Operator Name Example Result
+ Union $x + $y Union of $x and $y
== Equality $x == $y True if $x and $y have the same key/value pairs
!= Inequality $x != $y True if $x is not equal to $y
!== Non-identity $x !== $y True if $x is not identical to $y
Conditional Operator :There is one more operator called conditional operator. This first
evaluates an expression for a true or false value and then execute one of the two given
statements depending upon the result of the evaluation.
Page | 19
Ex: Arithmetic Operators:
<!DOCTYPE html>
<html >
<head>
<title>PHPArithmetic Operators</title>
</head>
<body>
<?php
$x = 10;
$y = 4;
echo($x + $y);
echo "<br>";
echo($x - $y);
echo "<br>";
echo($x * $y);
echo "<br>";
echo($x / $y);
echo "<br>";
echo($x % $y);
?>
</body>
</html>
Q) Flow-Control Statements in PHP:
Control flow statements are used to control the flow of execution of statements.
You can use control flow statements in your programs to conditionally execute
statements, to repeatedly execute a block of statements.
Generally, a program is executed sequentially, line by line, and a control structure
allows you to alter that flow, usually depending on certain conditions.
Types:
In PHP conditional statements are the statements which are used to deciding the
order of execution of statements based on certain conditions or perform different
types of actions based on different actions.
Page | 20
In PHP we have the following conditional statements:
if statement
if...else statement
if...elseif ...else statement
switch statement
If Statement:
Syntax : if (condition)
{
Ex:
<html>
<body>
<?php
$d = date("D");
if ($d == "Fri")
echo "Have a nice weekend!";
?>
</body>
</html>
Syntax : if (condition)
Page | 21
{
//code to be executed if condition is false;
}
Example
<html>
<body>
<?php
$d = date("D");
if ($d == "Fri")
echo "Have a nice weekend!";
else
echo "Have a nice day!";
?>
</body>
</html>
The PHP if-else-if is a special statement used to combine multiple if?.else statements. So,
we can check multiple conditions using this statement.
Syntax
if (condition)
{
//code to be executed if condition is true;
}
else if (condition)
{
//code to be executed if condition is true;
}
else
{
//code to be executed if condition is false;
}
Ex:
<html>
<body>
<?php
$d = date("D");
if ($d == "Fri")
Page | 22
echo "Have a nice weekend!";
elseif ($d == "Sun")
echo "Have a nice Sunday!";
else
echo "Have a nice day!";
?>
</body>
</html>
Switch:
PHP switch statement is used to execute one statement from multiple conditions. It
works like PHP if-else-if statement.
The switch statement works with two other keywords: case and break.
The case keyword is used to test a label against a value from the round brackets.
If the label equals to the value, the statement following the case is executed. The break
keyword is used to jump out of the switch statement.
Syntax
switch(expression)
{
case value1:
//code to be executed
break;
case value2:
//code to be executed
break;
......
default:
code to be executed if all cases are not matched;
}
Example:
<html>
<body>
<?php
$d = date("D");
switch ($d){
case "Mon":
echo "Today is Monday";
break;
Page | 23
case "Tue":
echo "Today is Tuesday";
break;
case "Wed":
echo "Today is Wednesday";
break;
case "Thu":
echo "Today is Thursday";
break;
case "Fri":
echo "Today is Friday";
break;
case "Sat":
echo "Today is Saturday";
break;
case "Sun":
echo "Today is Sunday";
break;
default:
echo "Wonder which day is this ?";
}
?>
</body>
</html>
While Loop
do While Loop
for Loop
for each loop
Page | 24
while Loop:
The while loop executes a block of code as long as the specified condition is true.
If the test condition is true then the code block will be executed. After the code has
executed the test condition will again be evaluated and the loop will continue until the
test expression is found to be false.
Syntax : do
{
code to be executed;
}
while (condition);
Example:
<html >
<head>
<title>PHP do-while Loop</title>
Page | 25
</head>
<body>
<?php
$i = 1;
do
{
$i++;
echo "The number is " . $i . "<br>";
}
while($i <= 3);
?>
</body>
</html>
For loop:
The PHP for loop allows the user to put all the loop-related statements (i.e.
INITIALIZER; CONDITION; INCREMENTOR or DECREMENTOR) in one place.
The structure is similar to C language.
Syntax
for ( initialization ; condition ; increment/decrement)
{
execute the statement;
}
initialize counter: Initialize the loop counter value.
test counter: Verify the loop counter whether the condition is true.
Increment/decrement counter: Increasing or decreasing the loop counter value.
Page | 26
PHP for each Loop:
The foreach loop is used to iterate over arrays.
Syntax:
foreach($array as $value){
// Code to be executed
}
Ex:
<html >
<head>
<title>PHP foreach Loop</title>
</head>
<body>
<?php
$colors = array("Red", "Green", "Blue");
foreach($colors as $value){
echo $value . "<br>";
}
?>
</body>
</html>
break Statement:
The PHP break keyword is used to terminate the execution of a loop prematurely.
The break statement is situated inside the statement block.
It gives you full control and whenever you want to exit from the loop you can come
out. After coming out of a loop immediate statement to the loop will be executed
<html>
<body>
<?php
$i = 0;
while( $i < 10) {
$i++;
if( $i == 3 )break;
}
echo ("Loop stopped at i = $i" );
?>
</body>
</html>
Page | 27
Continue:
"Continue is used within looping structures to skip the rest of the current loop iteration"
and continue execution. It is used to halt the current iteration of a loop but it does not
terminate the loop.
<html>
<body>
<?php
$array = array( 1, 2, 3, 4, 5);
foreach( $array as $value ) {
if( $value == 3 )continue;
echo "Value is $value <br />";
}
?>
</body>
</html>
Page | 28
</body>
</html>
If $display_prices is set to true in line 7, the table is printed. For the sake of readability, we
split the output into multiple print() statements.
Put these lines into a text file called testmultiprint.php, and place this file in your Web server
document root. When you access this script through your Web browser, it should look like
.
There's nothing wrong with the way this is coded, but we can save ourselves some typing
by simply slipping back into HTML mode within the code block.
Returning to HTML Mode Within a Code Block
<html>
<head>
<title>table</title>
</head>
<body>
<?php
$displayprices = true;
if ( $displayprices )
{
?>
<table border="1">
<tr><td colspan="3">today's prices in dollars</td></tr>
<tr><td>14</td><td>32</td><td>71</td>
</table>
<?php
}
?>
</body>
</html>
The important thing to note here is that the shift to HTML mode on line 9 only occurs if the
condition of the if statement is fulfilled. This can save us the bother of escaping quotation
marks and wrapping our output in print() statements. It might, however, affect the
readability of our code in the long run, especially as our script grows larger.
Page | 29
Functions:
A Function in PHP is a reusable piece or block of code that performs a specific action.
It takes input from the user in the form of parameters, performs certain actions, and
gives the output.
Functions can either return values when called or can simply perform an operation
without returning any value.
Functions reduce the repetition of code within a program — Function allows you
to extract commonly used block of code into a single component. Now you can perform the
same task by calling this function wherever you want within your script without having to
copy and paste the same block of code again and again.
Functions makes the code much easier to maintain — Since a function created once
can be used many times, so any changes made inside a function automatically implemented
at all the places without touching the several files.
Functions Syntax:
Page | 30
Syntax : function functionName()
{
code to be executed;
}
Calling a Function:
To call a function in php we use the name of the function ended by semicolon;
syntax : functionname();
Example:
<html>
<head>
<title>Writing PHP Function</title>
</head>
<body>
<?php
function Message()
{
echo " Have a nice day";
}
Message();
Message();
?>
</body>
</html>
The variables 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.
{
executable code;
}
Page | 31
EX:<html>
<head>
<title>Writing PHP Function with Parameters</title>
</head>
<body>
<?php
function addFunction($num1, $num2,$num3)
{
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
addFunction(10, 20);
?>
</body>
</html>
Call By Reference
EX: functionref.php
<html>
<head>
<title>Writing PHP call by reference</title>
</head>
<body>
<?php
function adder(&$str2)
{
$str2 .= 'Call By Reference';
}
$str = 'Hello ';
adder($str);
echo $str;
?>
</body>
</html>
Page | 32
Function with Default Arguments:
File: functiondefaultarg.php
<html>
<head>
<title>Writing PHP Function with default arguments</title>
</head>
<body>
<?php
function sayHello($name="lakshmi")
{
echo "Hello $name<br/>";
}
sayHello("Rajesh");
sayHello();
sayHello("John");
?>
</body>
</html>
Output: Hello Rajesh
Hello mahesh
Hello John
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.
ex:functiondefaultarg.php
<html>
<head>
<title>Writing PHP Function with returning value</title>
</head>
<body>
<?php
function cube($n){
return $n*$n*$n;
}
echo "Cube of 3 is: ".cube(3);
?>
</body>
</html>
Page | 33
Output: Cube of 3 is: 27
Page | 34
Arrays:
Arrays in PHP are a type of data structure that allows us to store multiple elements of
similar data type under a single variable.
The arrays are helpful to create a list of elements of similar types, which can be
accessed using their index or key.
For example if you want to store 100 numbers then instead of defining 100 variables
its easy to define an array of 100 length.
An array can hold any number of values, including no values at all.
Each value in an array is called an element.
You access each element via its index, which is a numeric or string value. Every
element in an array has its own unique index.
An element can store any type of value, such as an integer, a string, or a Boolean. You
can mix types within an array — for example, the first element can contain an integer,
the second can contain a string, and so on.
An array’s length is the number of elements in the array.
Types of Arrays:
Numerical Arrays:
These arrays can store numbers, strings and any object but their index will be
represented by numbers.
By default, the index starts at zero.
All PHP array elements are assigned to an index number by default.
Page | 35
These arrays can be created in two different ways.
Page | 36
Value is 4
Value is 5
Value is one
Value is two
Value is three
Value is four
Value is five
AssociativeArrays
An array with a string index where instead of linear storage, each value can be
assigned a specific key.
Associative array will have their index as string so that you can establish a strong
association between key and values.
To store the salaries of employees in an array, a numerically indexed array would not
be the best choice. Instead, we could use the employees names as the keys in our
associative array, and the value would be their respective salary.
We can associate name with each array elements in PHP using => symbol.
or
or
$age['samivulla'] = "21";
$age['raviteja'] = "20";
$age['rajesh'] = "19"
Ex: <?php
$salary=array("Samivulla"=>"350000","venkat"=>"450000","Kartik"=>"200000");
echo "Samivulla salary: ".$salary["samivulla"]."<br/>";
echo "Venkat salary: ".$salary[vekat"]."<br/>";
echo "Kartik salary: ".$salary["Kartik"]."<br/>"; ?>
Page | 37
Output:
Samivulla salary:350000
venkatsalary: 450000
Kartiksalary: 200000
MultidimensionalArrays
PHP multidimensional array is also known as array of arrays.
It allows you to store tabular data in an array.
PHP multidimensional array can be represented in the form of matrix which is
represented by row * column.
Syntax:
$arrayname=array(
array(value1,value2,value3),
array(value1,value2,value3),
array(value1,value2,value3)
);
Ex:
<?php
$emp = array
(
array(1,"Samivulla",350000),
array(2,"venkat",450000),
array(3,"karthik",200000)
);
for ($row = 0; $row < 3; $row++)
{
for ($col = 0; $col < 3; $col++)
{
echo $emp[$row][$col]." ";
}
echo "<br/>";
}
?>
Page | 38
Q) Functions of Array:
Ex: <?php
$names=array("lakshmi","anusha","aparna");
echo "$names[0]<br>$names[1]<br>$names[2]";
?>
Output: Sireesha
Anusha
aparna
Ex: <?php
$names=array("lakshmi","anusha","aparna");
echo count($names);
?>
Output: 3
Syntax :sort(array);
Ex: <?php
$names=array("lakshmi","anusha","aparna","ramesh","suresh");
sort($names);
$length=count($names);
for($x=0;$x<$length;$x++)
echo $names[$x];
Page | 39
echo "<br>";
?>
Output: anusha
aparna
lakshmi
ramesh
suresh
4. array_push() Function:
The array_push() function inserts one or more elements to the end of an array.
Syntax : array_push(array, value1, value2, ...);
Ex: <?php
$names=array("lakshmi","anusha","aparna");
array_push($names,"janaki","amrutha");
print_r($names)
?>
5. array_pop() Function:
The array_pop() function deletes the last element of an array.
Syntax : array_pop(array);
Ex: <?php
$names=array("lakshmi","anusha","aparna");
array_pop($names);
print_r($names)
?>
6. array_reverse() Function:
The array_reverse() function returns an array in the reverse order.
Syntax : array_reverse(array);
Ex: <?php
$names=array("lakshmi","anusha","aparna");
array_reverse($names);
print_r($names);
?>
7. array_replace() Function:
It Replace the values of the first array ($a1) with the values from the second array
($a2).
Syntax: array_replace(array1, array2, array3, ...);
Page | 40
Ex: <?php
$names1=array("lakshmi","anusha","aparna");
$names2=array("ram","venkat","kishore");
print_r(array_replace($names1,$names2));
?>
8. array_shift() Function:
The array_shift() function removes the first element from an array, and
returns the value of the removed element.
Syntax : array_shift(array);
Ex: <?php
$names=array("jayasree","lakshmi","anusha","aparna");
array_shift($names);
print_r($names);
?>
9. array_unshift() Function:
The array_unshift() function inserts new elements to an array. The new array values
will be inserted in the beginning of the array.
Syntax : array_unshift(array, value1, value2, value3, ...);
Ex: <?php
$names=array("jayasree","lakshmi","anusha","aparna");
array_unshift($names,"ram");
print_r($names);
?>
10. array_slice() Function:
The array_slice() function returns selected parts of an array.
Syntax : array_slice(array, start, length);
Ex: <?php
$names=array("jayasree","lakshmi","anusha","aparna","ram","suresh","venk
at");
print_r(array_slice($names,2,4));
?>
Ex: <?php
$names1=array("jayasree","lakshmi","anusha","aparna","ram");
Page | 41
$names2=array("venkat","kishore","ramesh");
array_splice($names1,0,2,$names2);
print_r($names1)
?>
12. array_search() Function:
The array_search() function search an array for a value and returns the key.
Syntax : array_search(value, array);
Ex: <?php
$names=array("jayasree","lakshmi","anusha","aparna","ram");
echo array_search("lakshmi",$names);
?>
13. array_sum() Function:
The array_sum() function returns the sum of all the values in the array.
Syntax: array_sum(array);
Ex: <?php
$a=array(5,15,25);
echo array_sum($a);
?>
14. PHP array_intersect() function
PHP array_intersect() function returns the intersection of two array. In other words, it
returns the matching elements of two array.
Syntax:
array array_intersect ( array $array1 , array $array2 [, array $... ] )
Example
<?php
$name1=array("sonoo","john","vivek","smith");
$name2=array("umesh","sonoo","kartik","smith");
$name3=array_intersect($name1,$name2);
foreach( $name3 as $n )
{
echo "$n<br />";
}
?>
15. rsort() Function:
The rsort() function sorts the values of the indexed array in descending order.
Syntax
rsort(array);
<?php
$fruits = array("apple", "orange", "mango", "banana", "kiwi");
rsort($fruits);
print_r($fruits);?>
Page | 42