Php1 and 2unit Notes
Php1 and 2unit Notes
PHP
PHP (recursive acronym for PHP: Hypertext Preprocessor) is a widely-used open source
general-purpose scripting language that is especially suited for web development and can be
embedded into HTML. It allows web developers to create dynamic content that interacts with
databases. PHP is basically used for developing web based software applications.
PHP is mainly focused on server-side scripting, so you can do anything any other CGI
program can do, such as collect form data, generate dynamic page content, or send and
receive cookies. Code is executed in servers, that is why you’ll have to install a sever-like
environment enabled by programs like XAMPP which is an Apache distribution.
1.1 Introduction
Back in 1994, Rasmus Lerdorf unleashed the very first version of PHP. However, now the
reference implementation is now produced by The PHP Group. The term PHP originally
stood for Personal Home Page but now it stands for the recursive acronym: Hypertext
Preprocessor. PHP 4 and PHP 5 are distributed under the PHP Licence v3.01, which is an
Open Source licence certified by the Open Source Initiative.
pg. 1
[Document title]
Why PHP?
There stand convincing arguments for all those who wonder why PHP is so popular today:
A web server is an information technology that processes requests via HTTP, the basic
network protocol used to distribute information on the World Wide Web. There exist many
types of web servers that servers use. Some of the most important and well-known are:
Apache HTTP Server, IIS (Internet Information Services), lighttpd, Sun Java System Web
Server etc. As a matter of fact, PHP is compatible with all these web servers and many more.
Unlike some technologies that require a specific operating system or are built specifically
for that, PHP is engineered to run on various platforms like Windows, Mac OSX, Linux,
Unix etc)
An important reason why PHP is so used today is also related to the various databases it
supports (is compatible with). Some of these databases are: DB++, dBase, Ingres, Mongo,
MaxDB, MongoDB, mSQL, Mssql, MySQL, OCI8, PostgreSQL, SQLite, SQLite3 and so
on.
Anyone can start using PHP right now by downloading it from php.net. Millions of people
are using PHP to create dynamic content and database-related applications that make for
outstanding web systems. PHP is also open source, which means the original source code is
made freely available and may be redistributed and modified.
PHP is a simple language to learn step by step. This makes it easier for people to get engaged
in exploring it. It also has such a huge community online that is constantly willing to help
you whenever you’re stuck (which actually happens quite a lot).
The graphic below shows a basic workflow of dynamic content being passed to and from the
client using PHP:
Figure 1.1: PHP Dynamic Content Interaction
XAMPP Setup
XAMPP is a free and open source cross-platform web server solution developed by Apache Friends, consisting mainly of the
Apache HTTP Server, MariaDB database, and interpreters for scripts written in the PHP and Perl programming languages. In
order to make your PHP code execute locally, first install XAMPP.
• Download XAMPP
• Install the program (check the technologies you want during installation)
• Open XAMPP and click on "Start" on Apache and MySQL (when working with databases)
Figure 1.2: XAMPP window after a successful installation with Apache and MySQL enabled
• Place your web project inside the htdocsdirectory. In the common case, if you installed XAMPP directly inside the C: driveof
your PC, the path to this folder would be: C:xampphtdocs
To test the services are up and running you can just enter localhost in your address bar and
expect the welcoming page.
PHP Language Basics
The aim of this section is to introduce the general syntax you should expect in PHP.
Escaping to PHP
There are four ways the PHP parser engine can differentiate PHP code in a webpage:
• Canonical PHP Tags
This is the most popular and effective PHP tag style and looks like this:
<?php...?>
• Short-open Tags
These are the shortest option, but they might need a bit of configuration, and you might
either choose the --enable-short-tags configuration option when building PHP, or set the
short_open_tag setting in your php.ini file.
<?...?>
• ASP-like Tags
In order to use ASP-like tags, you’ll need to set the configuration option in the php.ini file:
<%...%>
You can define a new script with an attribute language like so:
<script language="PHP">...</script>
Just like other languages, there are several ways to comment PHP code. Let’s
have a look at the most useful ones: Use #to write single-line comments
<?
# this is a comment in PHP, a single line comment
?>
<?
// this is also a comment in PHP, a single line comment
?>
The result of the above statements would be the same: "Hello World". But why are there three different ways to output?
1. boolean
2. integer
3. float
4. string
It can hold multiple values. There are 2 compound data types in PHP.
1. array
2. object
PHP Integer
Integer means numeric data with a negative or positive sign. It holds only whole numbers, i.e.,
numbers without fractional part or decimal points.
Example:
1. <?php
2. $dec1 = 34;
3. $oct1 = 0243;
4. $hexa1 = 0x45;
5. echo "Decimal number: " .$dec1. "</br>";
6. echo "Octal number: " .$oct1. "</br>";
7. echo "HexaDecimal number: " .$hexa1. "</br>";
8. ?>
Output:
Decimal number: 34
Octal number: 163
HexaDecimal number: 69
PHP Float
A floating-point number is a number with a decimal point. Unlike integer, it can hold numbers
with a fractional or decimal point, including a negative or positive sign.
Example:
1. <?php
2. $n1 = 19.34;
3. $n2 = 54.472;
4. $sum = $n1 + $n2;
5. echo "Addition of floating numbers: " .$sum;
6. ?>
Output:
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. But both are treated differently.
To clarify this, see the example below:
Example:
1. <?php
2. $company = "Javatpoint";
3. //both single and double quote statements will treat different
4. echo "Hello $company";
5. echo "</br>";
6. echo 'Hello $company';
7. ?>
Output:
Hello Javatpoint
Hello $company
PHP Array
An array is a compound data type. It can store multiple values of same data type in a single variable.
Example:
1. <?php
2. $bikes = array ("Royal Enfield", "Yamaha", "KTM");
3. var_dump($bikes); //the var_dump() function returns the datatype and values
4. echo "</br>";
5. echo "Array Element1: $bikes[0] </br>";
6. echo "Array Element2: $bikes[1] </br>";
7. echo "Array Element3: $bikes[2] </br>";
8. ?>
Output:
array(3) { [0]=> string(13) "Royal Enfield" [1]=> string(6) "Yamaha" [2]=> string(3) "KTM" }
Array Element1: Royal Enfield
Array Element2: Yamaha
Array Element3: KTM
PHP object
Objects are the instances of user-defined classes that can store both values and functions. They must be explicitly
declared.
Example:
1. <?php
2. class bike {
3. function model() {
4. $model_name = "Royal Enfield";
5. echo "Bike Model: " .$model_name;
6. }
7. }
8. $obj = new bike();
9. $obj -> model();
10. ?>
Output:
Keywords in Php:
$x = 7;
// Define a conditional statement
if ($x == 5) {
echo "x is equal to 5.";
}
// Define a loop
for ($i = 0; $i < 10; $i++) {
echo $i;
}
// Define a function
function add($a, $b)
{
return $a + $b;
}
?>
PHP Constants
PHP constants are name or identifier that can't be changed during the execution of the script . PHP
constants can be defined by 2 ways:
Constants are similar to the variable except once they defined, they can never be undefined or
changed. They remain constant across the entire program. PHP constants follow the same PHP
variable rules. For example, it can be started with a letter or underscore only.
Use the define() function to create a constant. It defines constant at run time. Let's see the syntax of define() function
in PHP.
Ex:
<?php
define("MESSAGE","Hello JavaTpoint PHP");
echo MESSAGE;
?>
Output:
<?php
const MESSAGE="Hello const by JavaTpoint PHP";
echo MESSAGE;
?>
Output:
Constant() function
There is another way to print the value of constants using constant() function instead of using the echo statement.
Example:
<?php
define("MSG", "JavaTpoint");
echo MSG, "</br>";
echo constant("MSG");
//both are similar
?>
Variables in PHP
Any type of variable in PHP starts with a leading dollar sign ($) and is assigned a variable
type using the = (equals) sign. The value of a variable is the value of its most recent
assignment.
Syntax :
$variablename=value;
Example
$x = 5;
$y = "John"
In the example above, the variable $x will hold the value 5, and the variable $y will hold the
value "John".
Note: When you assign a text value to a variable, put quotes around the value.
Note: Unlike other programming languages, PHP has no command for declaring a variable. It is
created the moment you first assign a value to it.
Rules for PHP variables:
• A variable starts with the $ sign, followed by the name of the variable
• A variable name must start with a letter or the underscore character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
• Variable names are case-sensitive ($age and $AGE are two different variables)
Example:
1. <?php
2. $str="hello string";
3. $x=200;
4. $y=44.6;
5. echo "string is: $str <br/>";
6. echo "integer is: $x <br/>";
7. echo "float is: $y <br/>";
8. ?>
Constant vs Variables
Constant Variables
Once the constant is defined, it can never be A variable can be undefined as well as redefined easily.
redefined.
A constant can only be defined using define() A variable can be defined by simple assignment (=) operator.
function. It cannot be defined by any simple
assignment.
There is no need to use the dollar ($) sign before To declare a variable, always use the dollar ($) sign before the
constant during the assignment. variable.
Constants do not follow any variable scoping rules, Variables can be declared anywhere in the program, but they
and they can be defined and accessed anywhere. follow variable scoping rules.
Constants are the variables whose values can't be The value of the variable can be changed.
changed throughout the program.
1. Local variable
2. Global variable
3. Static variable
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.
A variable declaration outside the function with the same name is completely different from the variable declared
inside the function. Let's understand the local variables with the help of an example:
1. <?php
2. function local_var()
3. {
4. $num = 45; //local variable
5. echo "Local variable declared inside the function is: ". $num;
6. }
7. local_var();
8. ?>
Output:
Ex:
<?php
function mytest()
{
$lang = "PHP";
echo "Web development language: " .$lang;
}
mytest();
//using $lang (local variable) outside the function will generate an error
PHP Programming Cookbook 16 / 63
echo $lang;
?>
Output:
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. 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.
Example:
1. <?php
2. $name = "Sanaya Sharma"; //Global Variable
3. function global_var()
4. {
5. global $name;
6. echo "Variable inside the function: ". $name;
7. echo "</br>";
8. }
9. global_var();
10. echo "Variable outside the function: ". $name;
11. ?>
Output:
Static variable
It is a feature of PHP to delete the variable, once it completes its execution and memory is freed. Sometimes we
need to store a variable even after completion of function execution. Therefore, another important feature of
variable scoping is static variable. We use the static keyword before the variable to define a variable, and this
variable is called as static variable.
Static variables exist only in a local function, but it does not free its memory after the program execution leaves
the scope. Understand it with the help of an example:
Example:
1. <?php
2. function static_var()
3. {
4. static $num1 = 3; //static variable
5. $num2 = 6; //Non-static variable
6. //increment in non-static variable
7. $num1++;
8. //increment in static variable
9. $num2++;
10. echo "Static: " .$num1 ."</br>";
11. echo "Non-static: " .$num2 ."</br>";
12. }
13.
14. //first function call
15. static_var();
Output:
Static: 4
Non-static: 7
Static: 5
Non-static: 7
You have to notice that $num1 regularly increments after each function call, whereas $num2 does not. This is
why because $num1 is not a static variable, so it freed its memory after the execution of each function call.
PHP Programming Cookbook 18 / 63
PHP Operators
PHP Operator is a symbol i.e used to perform operations on operands. In simple words, operators are used to
perform operations on variables or values. For example:
In the above example, + is the binary + operator, 10 and 20 are operands and $num is variable.
o Arithmetic Operators
o Assignment Operators
o Bitwise Operators
o Comparison Operators
o Incrementing/Decrementing Operators
o Logical Operators
o String Operators
o Array Operators
We can also categorize operators on behalf of operands. They can be categorized in 3 forms:
Arithmetic Operators
The PHP arithmetic operators are used to perform common arithmetic operations such as addition, subtraction, etc.
with numeric values.
PHP Programming Cookbook 19 / 63
Assignment Operators
The assignment operators are used to assign value to different variables. The basic assignment operator is "=".
Bitwise Operators
The bitwise operators are used to perform bit-level operations on operands. These operators allow the evaluation
and manipulation of specific bits within the integer.
& And $a & $b Bits that are 1 in both $a and $b are set to 1, otherwise 0.
~ Not ~$a Bits that are 1 set to 0 and bits that are 0 are set to 1
<< Shift left $a << $b Left shift the bits of operand $a $b steps
>> Shift right $a >> $b Right shift the bits of $a operand by $b number of places
Comparison Operators
Comparison operators allow comparing two values, such as number or string. Below the list of comparison
operators are given:
=== Identical $a === $b Return TRUE if $a is equal to $b, and they are of same data
type
!== Not identical $a !== $b Return TRUE if $a is not equal to $b, and they are not of same
data type
<= Less than or equal to $a <= $b Return TRUE if $a is less than or equal $b
>= Greater than or equal $a >= $b Return TRUE if $a is greater than or equal $b
to
Incrementing/Decrementing Operators
The increment and decrement operators are used to increase and decrease the value of a variable.
Logical Operators
The logical operators are used to perform bit-level operations on operands. These operators allow the evaluation
and manipulation of specific bits within the integer.
xor Xor $a xor $b Return TRUE if either $ or $b is true but not both
String Operators
The string operators are used to perform the operation on strings. There are two string operators in PHP, which are
given below:
.= Concatenation and $a .= $b First concatenate $a and $b, then assign the concatenated
Assignment string to $a, e.g. $a = $a . $b
Array Operators
The array operators are used in case of array. Basically, these operators are used to compare the values of arrays.
=== Identity $a === $b Return TRUE if $a and $b have same key/value pair of same type in
same order
For controlling the flow of the program, the control statements are beneficial
for the flow of execution of statements.
The Control Statements in PHP are divided into three types which
are Conditional/Selection statements, Iteration/Loop statements, and Jump statements.
PHP Programming Cookbook 23 / 63
<?php
$x = 12;
if ($x > 0) {
echo "The number is positive";
}
?>
Output:
The number is positive
Flowchart:
PHP Programming Cookbook 24 / 63
2. if…else Statement: We understood that if a condition will hold i.e., TRUE, then the block
of code within if will be executed. But what if the condition is not TRUE and we want to
perform an action? This is where else comes into play. If a condition is TRUE then if block
gets executed, otherwise else block gets executed.
Syntax:
if (condition) {
// if TRUE then execute this code
}
else{
// if FALSE then execute this code
}
Example:
<?php
$x = -12;
if ($x > 0) {
echo "The number is positive";
}
else{
echo "The number is negative";
}
PHP Programming Cookbook 25 / 63
?>
Output:
The number is negative
Flowchart:
3. if…elseif…else Statement: This allows us to use multiple if…else statements. We use this
when there are multiple conditions of TRUE cases.
Syntax:
4. if (condition) {
5. // if TRUE then execute this code
6. }
7. elseif {
8. // if TRUE then execute this code
9. }
10. elseif {
11. // if TRUE then execute this code
12. }
13. else {
PHP Programming Cookbook 26 / 63
<?php
$x = "August";
if ($x == "January") {
echo "Happy Republic Day";
}
else{
echo "Nothing to show";
}
?>
Output:
Happy Independence Day!!!
Flowchart:
PHP Programming Cookbook 27 / 63
switch Statement: The “switch” performs in various cases i.e., it has various cases to which it
matches the condition and appropriately executes a particular case block. It first evaluates an
expression and then compares with the values of each case. If a case matches then the same case
is executed. To use switch, we need to get familiar with two different keywords
namely, break and default.
1. The break statement is used to stop the automatic control flow into the next
cases and exit from the switch case.
2. The default statement contains the code that would execute if none of the cases
match.
PHP Programming Cookbook 28 / 63
Syntax:
switch(n) {
case statement1:
code to be executed if n==statement1;
break;
case statement2:
code to be executed if n==statement2;
break;
case statement3:
code to be executed if n==statement3;
break;
case statement4:
code to be executed if n==statement4;
break;
......
default:
code to be executed if n != any case;
Example:
<?php
$n = "February";
switch($n) {
case "January":
echo "Its January";
break;
case "February":
echo "Its February";
break;
case "March":
echo "Its March";
break;
case "April":
echo "Its April";
break;
case "May":
echo "Its May";
break;
case "June":
PHP Programming Cookbook 29 / 63
Output:
Its February
Flowchart:
PHP Programming Cookbook 30 / 63
PHP Programming Cookbook 31 / 63
Ternary Operators
In addition to all this conditional statements, PHP provides a shorthand way of writing if…else,
called Ternary Operators. The statement uses a question mark (?) and a colon (:) and takes three
operands: a condition to check, a result for TRUE and a result for FALSE.
Syntax:
<?php
$x = -12;
if ($x > 0) {
echo "The number is positive \n";
}
else {
echo "The number is negative \n";
}
Output:
The number is negative
The number is negative
Loops in PHP
In PHP, just like any other programming language, loops are used to execute the same code block
for a specified number of times. Except for the common loop types (for, while, do. . . while),
PHP also support foreach loops, which is not only specific to PHP. Languages like Javascript
and C# already use foreach loops. Let’s have a closer look at how each of the loop types
works.
It should be used if the number of iterations is known otherwise use while loop. This means for loop is used when
you already know how many times you want to execute a block of code.
It allows users to put all the loop related statements in one place. See in the syntax given below:
PHP Programming Cookbook 32 / 63
Syntax
Parameters
The php for loop is similar to the java/C/C++ for loop. The parameters of for loop have the following meanings:
initialization - Initialize the loop counter value. The initial value of the for loop is done only once. This parameter
is optional.
condition - Evaluate each iteration value. The loop continuously executes until the condition is false. If TRUE, the
loop execution continues, otherwise the execution of the loop ends.
Flowchart
PHP Programming Cookbook 33 / 63
Example
1. <?php
2. for($n=1;$n<=10;$n++){
3. echo "$n<br/>";
4. }
5. ?>
Output:
1
2
3
4
5
6
7
8
9
10
The while loop is also called an Entry control loop because the condition is checked before entering the loop body.
This means that first the condition is checked. If the condition is true, the block of code will be executed.
Syntax
1. while(condition){
2. //code to be executed
3. }
Alternative Syntax
1. while(condition):
2. //code to be executed
3.
4. endwhile;
1. <?php
2. $n=1;
3. while($n<=10){
4. echo "$n<br/>";
5. $n++;
6. }
7. ?>
Output:
1
2
3
4
5
6
7
8
9
10
The PHP do-while loop is used to execute a set of code of the program several times. If you have to execute the
loop at least once and the number of iterations is not even fixed, it is recommended to use the do-while loop.
It executes the code at least one time always because the condition is checked after executing the code.
The do-while loop is very much similar to the while loop except the condition check. The main difference
between both loops is that while loop checks the condition at the beginning, whereas do-while loop checks the
condition at the end of the loop.
Syntax
1. do{
2. //code to be executed
3. }while(condition);
Flowchart
Example
1. <?php
2. $n=1;
3. do{
4. echo "$n<br/>";
5. $n++;
6. }while($n<=10);
7. ?>
PHP Programming Cookbook 36 / 63
Output:
1
2
3
4
5
6
7
8
9
PHP foreach loop
The foreach loop is used to traverse the array elements. It works only on array and object. It will issue an error if
you try to use it with the variables of different datatype.
The foreach loop works on elements basis rather than index. It provides an easiest way to iterate the elements of an
array.
Syntax
Syntax
Flowchart
Example 1:
PHP program to print array elements using foreach loop.
1. <?php
2. //declare array
3. $season = array ("Summer", "Winter", "Autumn", "Rainy");
4.
5. //access array elements using foreach loop
6. foreach ($season as $element) {
7. echo "$element";
8. echo "</br>";
9. }
10. ?>
Output:
Summer
Winter
Autumn
Rainy
PHP Break
PHP break statement breaks the execution of the current for, while, do-while, switch, and for-each loop. If you use
break inside inner loop, it breaks the execution of inner loop only.
The break keyword immediately ends the execution of the loop or switch structure. It breaks the current flow of
the program at the specified condition and program control resumes at the next statements outside the loop.
The break statement can be used in all types of loops such as while, do-while, for, foreach loop, and also with
switch case.
Syntax
jump statement;
break;
Flowchart
PHP Break: inside loop
Let's see a simple example to break the execution of for loop if value of i is equal to 5.
ADVERTISEMENT
1. <?php
2. for($i=1;$i<=10;$i++){
3. echo "$i <br/>";
4. if($i==5){
5. break;
6. }
7. }
8. ?>
Output:
1
2
3
4
The continue statement is used within looping and switch control structure when you immediately jump to the next
iteration.
The continue statement can be used with all types of loops such as - for, while, do-while, and foreach loop. The
continue statement allows the user to skip the execution of the code for the specified condition.
Syntax
The syntax for the continue statement is given below:
jump-statement;
continue;
Flowchart:
In the following example, we will print only those values of i and j that are same and skip others.
1. <?php
2. //outer loop
3. for ($i =1; $i<=3; $i++) {
4. //inner loop
5. for ($j=1; $j<=3; $j++) {
6. if (!($i == $j) ) {
7. continue; //skip when i and j does not have same values
8. }
9. echo $i.$j;
10. echo "</br>";
11. }
12. }
13. ?>
Output:
11
22
33
PHP Arrays
PHP array is an ordered map (contains value on the basis of key). It is used to hold multiple values of similar type
in a single variable.
Easy to traverse: By the help of single loop, we can traverse all the elements of an array.
1. Indexed Array
2. Associative Array
3. Multidimensional Array
1st way:
1. $season=array("summer","winter","spring","autumn");
2nd way:
1. $season[0]="summer";
2. $season[1]="winter";
3. $season[2]="spring";
4. $season[3]="autumn";
Example
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
4. ?>
Example:
1. <?php
2. $season[0]="summer";
3. $season[1]="winter";
4. $season[2]="spring";
5. $season[3]="autumn";
6. echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
7. ?>
Output:
1. <?php
2. $size=array("Big","Medium","Short");
3. echo count($size);
4. ?>
Output:
3
File: array3.php
1. <?php
2. $size=array("Big","Medium","Short");
3. foreach( $size as $s )
4. {
5. echo "Size is: $s<br />";
6. }
7. ?>
Output:
1st way:
1. $salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
2nd way:
1. $salary["Sonoo"]="350000";
2. $salary["John"]="450000";
3. $salary["Kartik"]="200000";
Example
1. <?php
2. $salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
3. echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
4. echo "John salary: ".$salary["John"]."<br/>";
5. echo "Kartik salary: ".$salary["Kartik"]."<br/>";
6. ?>
Output:
1. <?php
2. $salary["Sonoo"]="350000";
3. $salary["John"]="450000";
4. $salary["Kartik"]="200000";
5. echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
6. echo "John salary: ".$salary["John"]."<br/>";
7. echo "Kartik salary: ".$salary["Kartik"]."<br/>";
8. ?>
Output:
1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
3. foreach($salary as $k => $v) {
4. echo "Key: ".$k." Value: ".$v."<br/>";
5. }
6. ?>
Output:
Ex:
Access an item by referring to its index number:
$cars = array("Volvo", "BMW", "Toyota");
echo $cars[2];
Example
Access an item by referring to its key name:
$cars = array("brand" => "Ford", "model" => "Mustang", "year" => 1964);
echo $cars["year"];
Example
Display all array items, keys and values:by using foeeach loop
Definition
1. $emp = array
2. (
3. array(1,"sonoo",400000),
4. array(2,"john",500000),
5. array(3,"rahul",300000)
6. );
Syntax
Syntax for indexed arrays:
array(key=>value,key=>value,key=>value,etc.)
Parameter Values
Parameter Description
Example:
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>
Output:
Syntax
array_key_exists(key, array)
Parameter Values
Parameter Description
<?php
$a=array("Volvo"=>"XC90","BMW"=>"X5");
if (array_key_exists("Volvo",$a))
{
echo "Key exists!";
}
else
{
echo "Key does not exist!";
}
?>
Syntax
array_keys(array, value, strict)
Parameter Values
Parameter Description
value Optional. You can specify a value, then only the keys with this value are returned
• true - Returns the keys with the specified value, depending on type: the number 5
• false - Default value. Not depending on type, the number 5 is the same as the str
Example
Return an array containing the keys:
<?php
$a=array("Volvo"=>"XC90","BMW"=>"X5","Toyota"=>"Highlander");
print_r(array_keys($a));
?>
Output:Array ( [0] => Volvo [1] => BMW [2] => Toyota )
4.PHP array_merge()
Definition and Usage
The array_merge() function merges one or more arrays into one array.
Tip: You can assign one array to the function, or as many as you like.
Note: If two or more array elements have the same key, the last one overrides the others.
Note: If you assign only one array to the array_merge() function, and the keys are integers, the function returns a new
array with integer keys starting at 0 and increases by 1 for each value (See example below).
Tip: The difference between this function and the array_merge_recursive() function is when two or more array
elements have the same key. Instead of override the keys, the array_merge_recursive() function makes the value as an
array.
Syntax
array_merge(array1, array2, array3, ...)
Parameter Values
Parameter Description
Example
Merge two arrays into one array:
<?php
$a1=array("red","green");
$a2=array("blue","yellow");
print_r(array_merge($a1,$a2));
?>
Output: Array ( [0] => red [1] => green [2] => blue [3] => yellow )
5.PHP array_pop() Function
Syntax
array_pop(array)
Parameter Values
Parameter Description
Example
Delete the last element of an array:
<?php
$a=array("red","green","blue");
array_pop($a);
print_r($a);
?>
Output:
Array ( [0] => red [1] => green )
Note: Even if your array has string keys, your added elements will always have numeric keys (See example below).
Syntax
array_push(array, value1, value2, ...)
Parameter Values
Parameter Description
Example
Insert "blue" and "yellow" to the end of an array:
<?php
$a=array("red","green");
array_push($a,"blue","yellow");
print_r($a);
?>
Output: Array ( [0] => red [1] => green [2] => blue [3] => yellow )
Syntax
array_search(value, array, strict)
Parameter Values
Parameter Description
value Required. Specifies the value to search for
strict Optional. If this parameter is set to TRUE, then this function will search for identical
elements in the array. Possible values:
• true
• false - Default
ADVERTISEMENT
Example
Search an array for the value "red" and return its key:
<?php
$a=array("a"=>"red","b"=>"green","c"=>"blue");
echo array_search("red",$a);
?>
Note: If the keys are numeric, all elements will get new keys, starting from 0 and increases by 1 (See example below).
Syntax
array_shift(array)
Parameter Values
Parameter Description
Example
Remove the first element (red) from an array, and return the value of the removed element:
<?php
$a=array("a"=>"red","b"=>"green","c"=>"blue");
echo array_shift($a);
print_r ($a);
?>
Note: If the array have string keys, the returned array will always preserve the keys (See example 4).
Syntax
array_slice(array, start, length, preserve)
Parameter Values
Parameter Description
length Optional. Numeric value. Specifies the length of the returned array. If this value is set to
a negative number, the function will stop slicing that far from the last element. If this
value is not set, the function will return all elements, starting from the position set by the
start-parameter.
preserve Optional. Specifies if the function should preserve or reset the keys. Possible values:
Example
Start the slice from the third array element, and return the rest of the elements in the array:
<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,2));
?>
Note: If the array have string keys, the returned array will always preserve the keys (See example 4).
Syntax
array_slice(array, start, length, preserve)
Parameter Values
Parameter Description
start Required. Numeric value. Specifies where the function will start the slice. 0 = the first
element. If this value is set to a negative number, the function will start slicing that far from
the last element. -2 means start at the second last element of the array.
length Optional. Numeric value. Specifies the length of the returned array. If this value is set to a
negative number, the function will stop slicing that far from the last element. If this value is
not set, the function will return all elements, starting from the position set by the start-
parameter.
preserve Optional. Specifies if the function should preserve or reset the keys. Possible values:
Example
Start the slice from the third array element, and return the rest of the elements in the array:
<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,2));
?>
Tip: If the function does not remove any elements (length=0), the replaced array will be inserted from the position of
the start parameter (See Example 2).
Note: The keys in the replaced array are not preserved.
Parameter Description
length Optional. Numeric value. Specifies how many elements will be removed.
array Optional. Specifies an array with the elements that will be inserted to the original array.
Syntax
array_splice(array, start, length, array)
Parameter Values
Example
Remove elements from an array and replace it with new elements:
<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("a"=>"purple","b"=>"orange");
array_splice($a1,0,2,$a2);
print_r($a1);
?>
12.PHP count() Function
Definition and Usage
The count() function returns the number of elements in an array.
Syntax
count(array, mode)
Parameter Values
Parameter Description
Example
Return the number of elements in an array:
<?php
$cars=array("Volvo","BMW","Toyota");
echo count($cars);
?>
Difference between Indexed array and associative array:
The keys of an indexed array are integers which start at 0. Keys may be strings in the case of an associative array.
They are like single-column tables. They are like two-column tables.
The include and require statements are identical, except upon failure:
• require will produce a fatal error (E_COMPILE_ERROR) and stop the script
• include will only produce a warning (E_WARNING) and the script will continue
Syntax
include 'filename';
or
require 'filename';
example:
<html>
<body>
</body>
</html>
Difference between require() and include() Functions:
include() require()
The include() function will only produce a The require() will produce a fatal error
warning (E_WARNING) and the script will (E_COMPILE_ERROR) along with the warning and
continue to execute. the script will stop its execution.
The include() function generate various The require() function is more in recommendation and
functions and elements that are reused considered better whenever we need to stop the
across many pages taking a longer time for execution incase of availability of file, it also saves
the process completion. time avoiding unnecessary inclusions and generations.