0% found this document useful (0 votes)
3 views

Chapter 1 _ Introduction to PHP

Chapter 1 introduces PHP, covering the distinction between static and dynamic web pages, as well as client-side and server-side scripting languages. It details PHP's characteristics, syntax, data types, variables, and operators, highlighting its ease of use and efficiency. The chapter also explains how PHP is parsed and executed on a web server, providing a foundational understanding of the language.

Uploaded by

sujaltrivedib
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Chapter 1 _ Introduction to PHP

Chapter 1 introduces PHP, covering the distinction between static and dynamic web pages, as well as client-side and server-side scripting languages. It details PHP's characteristics, syntax, data types, variables, and operators, highlighting its ease of use and efficiency. The chapter also explains how PHP is parsed and executed on a web server, providing a foundational understanding of the language.

Uploaded by

sujaltrivedib
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 27

1 Chapter 1 : Introduction to PHP

Chapter 1 : Introduction to PHP

Web Page

Web page is a document available on world wide web. Web Pages are stored on web server
and can be viewed using a web browser.

A web page can contain huge information including text, graphics, audio, video and hyper
links. These hyperlinks are the link to other web pages. Collection of linked web pages on a
web server is known as website. There is unique Uniform Resource Locator (URL) is associated
with each web page.

Static Web page


Static web pages are also known as flat or stationary web page. They are loaded on the client’s
browser as exactly they are stored on the web server. Such web pages contain only static
information. User can only read the information but can’t do any modification or interact with
the information.

Static web pages are created using only HTML, CSS, Javascript. Static web pages are only used
when the information is no more required to be modified.

Dynamic Web page


Dynamic Web Pages are written in languages such as CGI, PHP, AJAX, ASP, ASP.NET, etc. In
dynamic web pages, the Content of pages is different for different visitors. It takes more time
to load than the static web page. Dynamic web pages are used where the information is
changed frequently, for example, stock prices, weather information, etc.
2 Chapter 1 : Introduction to PHP

Differnce between Static webpage and Dynamic Webpage

Static Web page Dynamic Web page


In static web pages, Pages will remain same In dynamic web pages, Content of pages are
until someone changes it manually. different for different visitors.
In static web pages, Information are change In dynamic web page, Information are change
rarely. frequently.
Static Web Page takes less time for loading Dynamic web page takes more time for
than dynamic web page. loading.
In Static Web Pages, database is not used. In dynamic web pages, database is used.
Static web pages are written in languages such Dynamic web pages are written in languages
as: HTML, JavaScript, CSS, etc. such as: PHP, ASP, JSP, etc.

Client Side Scripting Language

A client-side script is a program that is processed within the client browser. These kinds of
scripts are small programs which are downloaded, compiled and run by the browser. JavaScript
3 Chapter 1 : Introduction to PHP

is an important client-side scripting language and widely used in dynamic websites. The script
can be embedded within the HTML or stored in an external file.

External scripts are sent to the client from the server when they are requested. Scripts can also
be executed as a result of the user doing something like pressing a page button.

Client-side scripts can often be looked at if the user chooses to view the source code of the
page. JavaScript code is widely copied and recycled.

Examples of Client Side Scripting Languages are vbscript and javascript.

Server Side Scripting Language


A server-side script is processed on the web server when the user requests information. These
kinds of scripts can run before a web page is loaded. They are needed for anything that requires
dynamic data, such as storing user login details. Some common server-side languages
include PHP, ASP, JSP. These execute like programming languages on the server.

When a server-side script is processed, the request is sent to the server and the result is sent
back to the client. This is useful for websites which store large amounts of data, such as search
engines or social networks - it would be very slow for the client browser to download all the
data.

Difference between Client Side Scripting Language and Server Side Scripting
Language.

Client Side Scripting Language Server Side Scripting Language


It is used at the front end which users can see It is used at the backend where the source
from the browser. code is not viewable or hidden at the client
side (browser).
A browser runs the script for client-side A web server runs the script for server-side
scripting that is already present in the user’s scripting that creates the page which needs to
computer. be sent to the browser.
It does not connect to the databases that are It helps in connecting to the databases that
on the web server. are already present in the web server.
It is excellent for any case which requires user It is excellent for any area that requires
interaction. loading of dynamic data.
Languages commonly used for client-side Languages used in server scripting are
scripting are Javascript, VBscript etc. PHP,ASP, JSP.
It is less secure because the scripts are usually It is more secure than client side scripting as
not hidden from the client end. the server side scripts are usually hidden from
4 Chapter 1 : Introduction to PHP

the client end.


It runs on web server. It runs on user’s computer.

What is PHP ?

 PHP originally stood for Personal Home Page. However, now, it stands for Hypertext
Preprocessor
 PHP is an interpreted language, i.e., there is no need for compilation.
 PHP is faster than other scripting languages, for example, ASP and JSP.
 PHP is a server-side scripting language, which is used to manage the dynamic content of the
website.
 PHP can be embedded into HTML.
 PHP is an object-oriented language.
 PHP is an open-source scripting language.
 PHP is simple and easy to learn language.
 PHP was created by Rasmus Lerdorf in 1994. It’s currently maintained by the PHP
Development Team.

Characteristics of PHP :
There are many features given by PHP. All Features discussed below one by one.

1. Familiarity
5 Chapter 1 : Introduction to PHP

2. Simplicity
3. Efficiency
4. Security
5. Flexibility
6. Open source
7. Object Oriented

Familiarity : If you are in programming background then you can easily understand the PHP
syntax. And you can write PHP script because of most of PHP syntax inherited from other
languages like C or Pascal.

Simplicity : PHP provides a lot of pre-define functions to secure your data. It is also compatible
with many third-party applications, and PHP can easily integrate with other.

In PHP script there is no need to include libraries like c, special compilation directives like Java,
PHP engine starts execution from (<?) escape sequence and end with a closing escape sequence
(<?). In PHP script, there is no need to write main function. And also you can work with PHP
without creating a class.

Efficiency : PHP 4.0 introduced resource allocation mechanisms and more pronounced support
for object-oriented programming, in addition to session management features. Eliminating
unnecessary memory allocation.

Security : Several trusted data encryption options are supported in PHP’s predefined function
set. You can use a lot of third-party applications to secure our data, allowing for securing our
application.

Flexibility : You can say that PHP is a very flexible language because of PHP is an embedded
language you can embed PHP scripts with HTML, JAVA SCRIPT, WML, XML, and many others.
You can run your PHP script any device like mobile Phone, tabs, laptops, PC and other because
of PHP script execute on the server then after sending to the browser of your device.

Free :PHP is an open source programming language so you can download freely there is no
need to buy a licence or anything.

Object Oriented : PHP has added some object-oriented programming features, and Object
Oriented programming became possible with PHP 4. With the introduction of PHP 5, the PHP
6 Chapter 1 : Introduction to PHP

developers have really beefed up the object-oriented features of PHP, resulting in both more
speed and added features.

How PHP is parsed ?

How PHP works:

 First, the web browser sends an HTTP request to the web server, e.g., index.php.
 Second, the PHP preprocessor that locates on the web server processes PHP code to
generate the HTML document.
 Third, the web server sends the HTML document back to the web browser.

PHP Syntax
There are four ways to use PHP in your Webpage.

(1) Canonical PHP tags : The most universally effective PHP tag style is :

<?php...?>

If you use this style, you can be positive that your tags will always be correctly
interpreted.
(2) Short-open (SGML-style) tags : Short or short-open tags look like this :

<?...?>
If you want to use this type, then you have to follow below steps :
1. Open php.ini file
7 Chapter 1 : Introduction to PHP

2. Set short_open_tag attribute to On


3. Restart All Services.
(3) ASP-style tags :ASP-style tags look like this

<%...%>
If you want to use this type, then you have to follow below steps :
4. Open php.ini file
5. Set asp_tags attribute to On
6. Restart All Services.

(4) HTML script tags : HTML script tags look like this

<script language = "PHP">...</script>

PHP Comments

Comment in PHP code is a line that is not executed as a part of the program. Its only purpose is
to be read by someone who is looking at the code.

Comments can be used to:

 Let others understand your code


 Remind yourself of what you did - Most programmers have experienced coming back to
their own work a year or two later and having to re-figure out what they did. Comments
can remind you of what you were thinking when you wrote the code

PHP supports several ways of commenting

Single line Comment : Single line comment is specified with ‘//’ or ‘#’

Multiline Comment : Multiline comments are specified with ‘/* …. */’

PHP Datatypes
Datatype determines which type of value a variable can contain.

PHP supports the following data types:


8 Chapter 1 : Introduction to PHP

1. Integer : Integer is a whole number which stores number without decimal point. It
stores positive and negative whole number. Integer can be represented in Decimal,
Octal and Hexadecimal. Default is Decimal. Octal number is represented with leading 0
and hexadecimal number is represented with leader 0x or 0X.

<?php
$a=12;
$b=012;
$c=0x12;
echo “$a”; //12
echo “<br>$b”; //10
echo “<br>$c”; //18
?>
2. Double /Float : A float (floating point number) is a number with a decimal
point or a number in exponential form. The PHP var_dump() function
returns the data type and value.

<?php
$a=3.14;
$b=1.2e3;
$c=1.2e-3;
echo $a; //3.14
echo "<br> $b"; //1200
echo "<br> $c"; //0.0012
var_dump($a); // float(3.14)
?>

3. Boolean : Booleans can be either TRUE or FALSE.


$x=true;
$y=false;
Booleans are often used in conditional testing.

4. String : It is a collection of characters. You can specify string in either single quote(‘ ‘) or
double quote (“ “). Single quoted string is printed as literal, but double quoted string
replace variable with their value.

<?php
$a=”KBSSC”;
9 Chapter 1 : Introduction to PHP

echo “$a “; //KBSSC


echo “<br>”;
echo ‘$a’; //$a
?>
5. Null : Null is a special data type which can have only one value: NULL. A variable of data
type NULL is a variable that has no value assigned to it. If a variable is created
without a value, it is automatically assigned a value of NULL.

<?php
$x = "Hello world!";
$x = null;
var_dump($x); //NULL
?>
6. Array : An array stores multiple values in one single variable.

<?php
$cars = array("Volvo","BMW","Toyota");
print_r($cars); // Array ( [0] => Volvo [1] => BMW [2] => Toyota )
?>
7. Object : An object is an instance of the class.

<?php
class student {
public $rollno;
public $name;
public function display()
{
echo "Rollno : " . $this->rollno;
echo "<br> Name : ". $this->name;
}
}

$s=new student();
$s->rollno=1;
$s->name="BCA";
$s->display();
?>
8. Resource : The special resource type is not an actual data type. It is the storing of a
reference to functions and resources external to PHP.
A common example of using the resource data type is a database call.
10 Chapter 1 : Introduction to PHP

PHP Variable

Variables are "containers" for storing information. In PHP, a variable starts with the $ sign,
followed by the name of the variable.

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)

Scope of variable
Variable scope is known as its boundary within which it can be visible or accessed from code. In
other words, it is the context within which a variable is defined.

1. Local variable : A local scope is a restricted boundary of a variable within which code
block it is declared. That block can be a function, class or any conditional span. The
variable within this limited local scope is known as the local variable of that specific code
block.

<?php
$msg = “I am outside of function”;

function test()
{
$msg=”I am inside of function”;
echo $msg;
}
echo $msg;
test();

?>
2. Function parameter : Function parameters are declared after function name and inside
parenthesis. They are declared as typical variable.

<?php
$a=10;
$b=20;
11 Chapter 1 : Introduction to PHP

sum($a,$b);
function sum($x, $y)
{
$z=$x+$y;
echo $z;
}
?>
3. Global variable : As its name, the global scope provides widespread access to the
variable declared in this scope. Variables in global scope can be accessed from anywhere
from outside a function or class independent of its boundary.
PHP global variables can be defined by using global keyword. If we want to use global
variables inside a function, we have to prefix the global keyword with the variable.

<?php
$count = 10;
function display() {
global $count;
echo "$count <br/>"; //10
$count++;
}
display();
echo $count; //11
?>
4. Static variable : Static variables exist only in a local function, but it does not free its
memory after the program execution leaves the scope. We use the static keyword
before the variable to define a variable, and this variable is called as static variable.

<?php
function display()
{
static $num1 = 3; //static variable
$num2 = 6; //Non-static variable
$num1++;
$num2++;
echo "Static: " .$num1 ."</br>";
echo "Non-static: " .$num2 ."</br>";
}

display(); // 4 7

display(); // 5 7
?>
12 Chapter 1 : Introduction to PHP

Write a program for page counter.

<?php
count_page();
function count_page()
{
static $p=0;
$p++;
Echo “<br> Page count : $pc”;
}
?>

PHP Operators

Operators are used to perform operations on variables and values.

PHP divides the operators in the following groups:

 Arithmetic operators
 Assignment operators
 Comparison operators
 Logical operators
 Conditional operators
 String operators

Arithmetic Operators :

The PHP arithmetic operators are used with numeric values to perform common arithmetical
operations, such as addition, subtraction, multiplication etc.

Assume variable A holds 10 and variable B holds 20 then:


Operato
Description Example
r

+ Adds two operands A + B will give 30


- Subtracts second operand from the first A - B will give -10
* Multiply both operands A * B will give 200
/ Divide numerator by denumerator B / A will give 2
Modulus Operator and remainder of after an
% B % A will give 0
integer division
13 Chapter 1 : Introduction to PHP

++ Increment operator, increases integer value by one A++ will give 11


Decrement operator, decreases integer value by
-- A-- will give 9
one

Assignment Operators:
There are following assignment operators supported by PHP language:
Operato
Description Example
r

Simple assignment operator,


= Assigns values from right side C = A + B will assigne value of A + B into C
operands to left side operand

Add AND assignment operator,


It adds right operand to the left
+= C += A is equivalent to C = C + A
operand and assign the result
to left operand

Subtract AND assignment


operator, It subtracts right
-= operand from the left operand C -= A is equivalent to C = C - A
and assign the result to left
operand

Multiply AND assignment


operator, It multiplies right
*= operand with the left operand C *= A is equivalent to C = C * A
and assign the result to left
operand

Divide AND assignment


operator, It divides left
/= operand with the right operand C /= A is equivalent to C = C / A
and assign the result to left
operand

%= Modulus AND assignment C %= A is equivalent to C = C % A


operator, It takes modulus
14 Chapter 1 : Introduction to PHP

using two operands and assign


the result to left operand

Comparison Operators
The PHP comparison operators are used to compare two values (number or string):
Operator Name Example Result
== Equal $x == $y True if $x is equal to $y
True if $x is equal to $y, and
=== Identical $x === $y
they are of the same type
!= Not equal $x != $y True if $x is not equal to $y
<> Not equal $x <> $y True if $x is not equal to $y
True if $x is not equal to $y, or
!== Not identical $x !== $y
they are not of the same type
> Greater than $x > $y True if $x is greater than $y
< Less than $x < $y True if $x is less than $y
Greater than or True if $x is greater than or
>= $x >= $y
equal to equal to $y
True if $x is less than or equal
<= Less than or equal to $x <= $y
to $y

Logical Operators
There are following logical operators supported by PHP language

Operato
Description Example
r

(A && B)
Called Logical AND operator. If both
&& True if a and b are true, otherwise it
the operands are non zero then
And is false.
then condition becomes true.

Called Logical OR Operator. If any of (A || B)


||
the two operands are non zero then True if a or b or both are true,
Or
then condition becomes true. otherwise it is false.

! Called Logical NOT Operator. Use to !A


not reverses the logical state of its True if a is false otherwise it is false.
operand. If a condition is true then
15 Chapter 1 : Introduction to PHP

Logical NOT operator will make


false.

(A xor B)
xor Called Logical XOR Operator. True if either a or b is true but not
both, otherwise it is false.
Conditional Operator or ternary operator
Operato
Description Example
r

Conditional operator. It takes three


?: parameters i.e condition, true part $a = (10 > 5) ? 10:5;
and false part.

String Operator
The string operators are used to perform the operation on strings.

Operato
Description Example
r

Concatenation. It concatenates two $a= “hello”; $b=”bca;


.
or more strings. $c=$a.$b; //hellobca

$a= “hello”; $b=”bca;


.= Concatenation and Assignment
$a.=$b; //hellobca
Http methods

The Hypertext Transfer Protocol (HTTP) is designed to enable communications


between clients and servers.

HTTP works as a request-response protocol between a client and server.

1. Get method : GET is used to request data from a specified resource. GET is one of the
most common HTTP methods. Note that the query string (name/value pairs) is sent in
the URL of a GET request:

/test/demo_form.php?name1=value1&name2=value2

The get method is restricted to send up to 1024 characters only. Never use get method
if you want to send sensitive information like password, account number, etc.
16 Chapter 1 : Introduction to PHP

Get method cannot be used to send binary data like images, word document, etc. to the
server.

Get method is the default method.

PHP $_GET is a PHP super global variable which is used to collect form data after
submitting an HTML form with method="get".
Example 1 :

test_get.html
<html>
<body>

<a href="test_get.php?name=KBSSC&branch=BCA">Click me </a>

</body>
</html>
test_get.php

<?php
$a= $_GET[‘name’];
$b= $_GET[‘branch’];
echo “Name : $a”;
echo “<br>Branch : $b”;
?>

Example 2 :

get.html
<html>
<body>
<form method=get action=get.php>
Enter Name: <input type=text name=t1> <br>
Enter Branch: <input type=text name=t2> <br>
<input type=submit name=b1 value=Display>
</body>
</html>
get.php

<?php
$a= $_GET[‘t1’];
$b= $_GET[‘t2’];
17 Chapter 1 : Introduction to PHP

echo “Name : $a”;


echo “<br>Branch : $b”;
?>

2. Post method : Post method is also used to send user information to the server. The post
method does not have any restriction on the data size to be sent. The post method can
also be used to send ASCII as well as binary data. Post method is secure than get
method.

PHP $_POST is a PHP super global variable which is used to collect form data after
submitting an HTML form with method="post".

post.html
<html>
<body>
<form method=post action=post.php>
Enter Name: <input type=text name=t1> <br>
Enter Branch: <input type=text name=t2> <br>
<input type=submit name=b1 value=Display>
</body>
</html>
post.php

<?php
$a= $_POST[‘t1’];
$b= $_POST[‘t2’];
echo “Name : $a”;
echo “<br>Branch : $b”;
?>

Difference between get method and post method.

HTTP get method HTTP post method


GET is a method that sends information by POST is a method that transfers information
appending them to the page request. via HTTP header.
The form information is visible in the URL The form information is not visible in the URL
Limited amount of information is sent. Unlimited amount of information is sent
Helps to send non-sensitive data Helps to send sensitive data (passwords),
binary data (word documents, images)and
uploading files
Not very secure. More secure.
Possible to bookmark the page Not possible to bookmark the page
18 Chapter 1 : Introduction to PHP

$_REQUEST
PHP $_REQUEST is a PHP super global variable which is used to collect form data after
submitting an HTML form with either method="post" or method=”get”.

request.html

<html>
<body>
<form method=post action=request.php>
Enter Name: <input type=text name=t1> <br>
Enter Branch: <input type=text name=t2> <br>
<input type=submit name=b1 value=Display>
</body>
</html>
request.php

<?php
$a= $_REQUEST[‘t1’];
$b= $_REQUEST[‘t2’];
echo “Name : $a”;
echo “<br>Branch : $b”;
?>

Conditional statements
When we want to test condition, conditional statements are used.

If statement :

PHP if statement allows conditional execution of code. It is executed if condition is true.

If statement is used to executes the block of code exist inside the if statement only if the
specified condition is true.

Syntax :

if (condition)
{
statement(s)
19 Chapter 1 : Introduction to PHP

If…else Statement :

PHP if…else statement is executed whether condition is true or false.

If-else statement is slightly different from if statement. It executes one block of code if the
specified condition is true and another block of code if the condition is false.

Syntax :

if (condition)
{
statement(s)
}
else
{
Statement(s)
}

If-else-if Statement :

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 (condition1)
{
//code to be executed if condition1 is true
}
elseif (condition2)
{
//code to be executed if condition2 is true
}
elseif (condition3)
{
//code to be executed if condition3 is true
}
else
20 Chapter 1 : Introduction to PHP

{
//code to be executed if all given conditions are false
}

Nested if Statement

The nested if statement contains the if block inside another if block. The inner if statement
executes only when specified condition in outer if statement is true.

Syntax :

if (condition)
{
if (condition)
{
statement(s)
}
else
{
Statement(s)
}
}
else
{
if (condition)
{
statement(s)
}
else
{
Statement(s)
}
}

Switch…case statement

PHP switch statement is used to execute one statement from multiple conditions. It works like
PHP if-else-if statement.
21 Chapter 1 : Introduction to PHP

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;
}

Looping statements

Loops are used to execute the same block of code again and again, as long as a
certain condition is true.

In PHP, there are four loop types:

1. For loop
2. While loop
3. Do…while loop
4. Foreach loop

For loop :

The for loop is used when you know in advance how many times the script should run.

Syntax:

for(initialization;condition; increment/decrement)
{
//statement(s)
}

Example :

<?php
22 Chapter 1 : Introduction to PHP

For($i=1;$i<=5;$i++)
{
Echo $i;
}
?>

While loop :

The while loop executes a block of code as long as the specified condition is true.

Syntax :

initialization
while (condition)
{
statement(s)
increment/decrement
}

Example :

<?php
$i=1;
while($i<6)
{
echo $i;
$i=$i+1;
}
?>

Do…while loop :

The do...while loop will always execute the block of code once, it will then check the condition,
and repeat the loop while the specified condition is true.

Syntax:
23 Chapter 1 : Introduction to PHP

do
{
Statement(s)
Increment/decrement
} while (condition);

Example :

<?php
$i=1;
do
{
echo $i;
$i++;
}while($i<=5);

Foreach loop

The foreach loop works only on arrays, and is used to loop through each key/value pair in an
array.

Syntax :

foreach (array as $value)


statement

foreach (array as $key => $value)


statement

For every loop iteration, the value of the current array element is assigned to $value and the
array pointer is moved by one, until it reaches the last array element.
24 Chapter 1 : Introduction to PHP

Example :

<?php
$colors = array("red", "green", "blue");

foreach ($colors as $value)


{
echo "$value <br>";
}
?>

Output :
red
green
blue

<?php
$colors = array("red", "green", "blue");

foreach ($colors as $key=>$value)


{
echo "$key=$value <br>";
}
?>

Output :
0=red
1=green
2=blue

Array
An array is a data structure that stores one or more similar type of values in a single value. For
example if you want to store 100 numbers then instead of defining 100 variables its easy to
define an array of 100 length.
array() is used to create an array of elements.
There are three different kind of arrays and each array value is accessed using an IDc which is
called array index.
25 Chapter 1 : Introduction to PHP

1. Numeric array or indexed array : These arrays can store numbers, strings and any object
but their index will be represented by numbers. By default array index starts from zero.
array() is used to create an array of elements.

<?php
/* First method to create array. */
$numbers = array( 1, 2, 3, 4, 5);

foreach( $numbers as $value )


{
echo " $value <br>";
}

/* Second method to create array. */


$numbers[0] = "one";
$numbers[1] = "two";
$numbers[2] = "three";
$numbers[3] = "four";
$numbers[4] = "five";

foreach( $numbers as $value )


{
echo "$value <br>";
}
?>

2. Associative array : The associative arrays are very similar to numeric arrays in term of
functionality but they are different in terms of their index. 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.

<?php
/* First method to associate create array. */
$s = array("aaa" =>20000, "bbb" =>10000, "ccc" =>5000);

echo "Salary of aaa is ". $s['aaa'] . "<br>";


echo "Salary of bbb is ". $s['bbb']. "<br>";
echo "Salary of ccc is ". $s['ccc']. "<br>";
26 Chapter 1 : Introduction to PHP

/* Second method to create array. */


$s['aaa'] = 20000;
$s['bbb'] = 10000;
$s['ccc'] = 5000;

echo "Salary of aaa is ". $s['aaa'] . "<br>";


echo "Salary of bbb is ". $s['bbb']. "<br>";
echo "Salary of ccc is ". $s['ccc']. "<br>";
?>

3. Multidimensional array : A multi-dimensional array each element in the main array can
also be an array. And each element in the sub-array can be an array, and so on. Values in
the multi-dimensional array are accessed using multiple index.

<?php
$marks = array
(
"aaa" => array (
"php" => 35,
"sql" => 30,
"java" => 39
),

"bbb" => array (


"php" => 30,
"sql" => 32,
"java" => 29
),

"ccc" => array (


"php" => 31,
"sql" => 22,
"java" => 29
)
);

/* Accessing multi-dimensional array values */


echo "Marks for aaa in php : " ;
echo $marks['aaa']['php'] . "<br>";

echo "Marks for bbb in sql : ";


echo $marks['bbb']['sql'] . "<br>";
27 Chapter 1 : Introduction to PHP

echo "Marks for ccc in java : " ;


echo $marks['ccc']['java'] . "<br>";

//Another method to declare multidimensional array


$marks['aaa']['php']=35;
$marks['aaa']['sql']=30;
$marks['aaa']['java']=39;

$marks['bbb']['php']=30;
$marks['bbb']['sql']=32;
$marks['bbb']['java']=29;

$marks['ccc']['php']=31;
$marks['ccc']['sql']=22;
$marks['ccc']['java']=29;

/* Accessing multi-dimensional array values */


echo "Marks for aaa in php : " ;
echo $marks['aaa']['php'] . "<br>";

echo "Marks for bbb in sql : ";


echo $marks['bbb']['sql'] . "<br>";

echo "Marks for ccc in java : " ;


echo $marks['ccc']['java'] . "<br>";

?>

You might also like