Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
17 views22 pages

WT - Unit 4

This document provides an introduction to PHP programming, covering its features, syntax, and how to create and run PHP scripts. It explains the use of variables, constants, data types, and control structures, along with examples for better understanding. Additionally, it discusses the installation of PHP and web servers, as well as the execution of PHP code both in a browser and command prompt.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views22 pages

WT - Unit 4

This document provides an introduction to PHP programming, covering its features, syntax, and how to create and run PHP scripts. It explains the use of variables, constants, data types, and control structures, along with examples for better understanding. Additionally, it discusses the installation of PHP and web servers, as well as the execution of PHP code both in a browser and command prompt.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Dr.

Vamshi Krishna K
Associate Professor, Dept. of CSE, KHIT, Guntur
[email protected], 8143260297
Unit 4
PHP Programming: Introduction to PHP, Creating PHP script, Running PHP
script. Working with variables and constants: Using variables, Using constants, Data types,
Operators. Controlling program flow: Conditional statements, Control statements, Arrays,
functions.

Introduction to PHP
 Hypertext Preprocessor (PHP) is a server-side scripting language designed specifically for
web development, but it is also used as a general-purpose programming language.
 It is an open-source which means it is free to download and which is very simple to learn
and use. PHP contain text, HTML, CSS, JavaScript, and PHP code and is saved with “.php”
extension.
 Unlike client-side languages like JavaScript, which are executed on the user’s browser, PHP
scripts run on the server. The results are then sent to the client’s web browser as plain
HTML.
 PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.), is compatible with
almost all servers used today (Apache, IIS, etc.) andsupports a wide range of databases.
 PHP was created by Rasmus Lerdorf in 1994 but appeared in the market in 1995. PHP 8.2 is
the latest version of PHP, which was released on 22 November 2022.

What Can PHP Do?


 PHP can generate dynamic page content
 PHP can create, open, read, write, delete, and close files on the server
 PHP can collect form data
 PHP can send and receive cookies
 PHP can add, delete, modify data in your database
 PHP can be used to control user-access
 PHP can encrypt data

Features of PHP

Page 1
Dr. Vamshi Krishna K
Associate Professor, Dept. of CSE, KHIT, Guntur
[email protected], 8143260297
Using PHP
 Install a web server
 Install PHP
 Install a database, such as MySQL

You can install a server on your personal computer such as XAMPP server from the link below:
https://www.apachefriends.org/index.html

A PHP version and MySQL come out of the box when you install XAMPP server. You can use other
development server instead of XAMPP such as WAMPSERVER that you can download from here
(http://www.wampserver.com/en/).

How PHP Works?


PHP scripts are executed on the server. A typical flow of how PHP works is as follows:
 A user requests a PHP page via their web browser.
 The server processes the PHP code. The PHP interpreter parses the script, executes the code,
and generates HTML output.
 The server sends the generated HTML back to the client’s browser, which renders the web
page.

Creating PHP script


 The basic syntax of PHP is very similar to that of C and C++. A statement in PHP is any
expression that is followed by a semicolon (;). Any sequence of valid PHP statements that is
enclosed by the PHP tags is a valid PHP program.
 A PHP script can be placed anywhere in the document. A PHP script starts with <?php and
ends with ?>.
Example

Comments in PHP: A comment in PHP code is a line that is not read/executed as part of the
program. Its only purpose is to be read by someone who is looking at the code.
Example
// This is a single-line comment

# This is also a single-line comment

/* This is a multiple-lines comment block


that spans over multiple lines */

Page 2
Dr. Vamshi Krishna K
Associate Professor, Dept. of CSE, KHIT, Guntur
[email protected], 8143260297
PHP echo: PHP echo statement can be used to print the string, multi-line strings, escaping
characters, variable, array, etc. Some important points that you must know about the echo statement
are:
o echo is a statement, which is used to display the output.
o echo can be used with or without parentheses: echo(), and echo.
o echo does not return any value.
o We can pass multiple strings separated by a comma (,) in echo.
o echo is faster than the print statement.

Example
1)
<?php
echo "Hello by PHP echo";
?>

2)
<?php
$msg="Hello JavaTpoint PHP";
echo "Message is: $msg";
?>

PHP Print: PHP print statement can be used to print the string, multi-line strings, escaping
characters, variable, array, etc. Some important points that you must know about the echo statement
are:
o print is a statement, used as an alternative to echo at many times to display the output.
o print can be used with or without parentheses.
o print always returns an integer value, which is 1.
o Using print, we cannot pass multiple arguments.
o print is slower than the echo statement.

Example
1)
<?php
print "Hello by PHP print ";
print ("Hello by PHP print()");
?>

2)
<?php
$msg="Hello print() in PHP";
print "Message is: $msg";
?>

Running PHP script


 We are using XAMPP server software for writing PHP code. The default document root
directory is typically "C:\xampp\htdocs\" on Windows and "/opt/lamp/htdocs/" on Linux.
 However, you can change the default document root by modifying the DocumentRoot setting
in Apache server’s configuration file "httpd.conf".

Page 3
Dr. Vamshi Krishna K
Associate Professor, Dept. of CSE, KHIT, Guntur
[email protected], 8143260297
While on a Windows operating system, start the Apache server from the XAMPP control panel.

Browse to the "htdocs" directory. Save the following script as "hello.php" in it.
<?php
echo” Hello KHIT”
?>
Open a new tab in your browser and enter http://localhost/hello.php as the URL. You should see the
"Hello World" message in the browser window.

Executing PHP code from command prompt


You can run your PHP script from the command prompt. Let's assume you have the following
content in your "hello.php" file.
<?php
echo” Hello KHIT”
?>
Add the path of the PHP executable to your operating system’s path environment variable. For
example, in a typical XAMPP installation on Windows, the PHP executable "php.exe" is present in
"c:\xampp\php" directory. Add this directory in the PATH environment variable string.

Now runs this script as command prompt –


C:\xampp\htdocs>php hello.php

Using variables
 PHP Variables are one of the most fundamental concepts in programming. It is used to store
data that can be accessed and manipulated within your code.
 Variables in PHP are easy to use, dynamically typed (meaning that you do not need to
declare their type explicitly), and essential for creating dynamic, interactive web
applications.
 To declare a variable in PHP, you simply assign a value to it using the $ symbol followed
by the variable name.
$x = 5;
$y = "John";
Page 4
Dr. Vamshi Krishna K
Associate Professor, Dept. of CSE, KHIT, Guntur
[email protected], 8143260297
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)

Assigning Values to PHP Variables by Reference


 You can also use the way to assign values to PHP variables by reference. In this case, the new
variable simply references or becomes an alias for or points to the original variable. Changes
to the new variable affect the original and vice versa.
 To assign by reference, simply prepend an ampersand (&) to the beginning of the variable
which is being assigned (the source variable).
Example
<?php
$x = 10;
$y = &$x;
$z = $x+$y;
echo "x=". $x . " y=" . $y . " z = ". $z . "\n";
$y=20;
$z = $x+$y;
echo "x=". $x . " y=" . $y . " z = ". $z . "";
?>

PHP Variable Scope


The scope of a variable refers to where it can be accessed within the code. PHP variables can have
following scope
1) Local Scope or Local Variable
Variables declared within a function have local scope and cannot be accessed outside the function.
Any declaration of a variable outside the function with the same name (as within the function) is a
completely different variable.
Example:
<?php
$num = 60;
function local_var() {
// This $num is local to this function
// The variable $num outside the function
// is a completely different
$num = 50;
echo "Variable num inside function is: $num \n";
}
local_var();
// The $num outside function is a completely
// different from inside local_var()
echo "Variable num outside function is: $num";
?>

Page 5
Dr. Vamshi Krishna K
Associate Professor, Dept. of CSE, KHIT, Guntur
[email protected], 8143260297
2) Global Scope or Global Variable
The variables declared outside a function are called global variables. These variables can be
accessed directly outside a function. To get access within a function we need to use the “global”
keyword before the variable to refer to the global variable.
Example
<?php
$num = 20;
// Function to demonstrate use of global variable
function global_var() {
// We have to use global keyword before
// the variable $num to access within
// the function
global $num;
echo "Variable num inside function: $num \n";
}
global_var();
echo "Variable num outside function: $num \n";
?>

3) Static Variables
It is the characteristic of PHP to delete the variable. Once it completes its execution and the
memory is freed. But sometimes we need to store the variables even after the completion of
function execution. To do this, we use the static keywords and the variables are then called static
variables. PHP associates a data type depending on the value for the variable.
Example
<?php
// Function to demonstrate static variables
function static_var() {
// Static Variable
static $num = 5;
$sum = 2;
$sum++;
$num++;
echo $num, "\n";
echo $sum, "\n";
}
// First function call
static_var();
// Second function call
static_var();
?>

4) Superglobals
Superglobals are built-in arrays in PHP that are accessible from anywhere in the script, including
within functions. Common superglobals include $_GET, $_POST, $_SESSION, $_COOKIE,
$_SERVER, and $_GLOBALS.
Example
<?php
// Using $_SERVER superglobal to

Page 6
Dr. Vamshi Krishna K
Associate Professor, Dept. of CSE, KHIT, Guntur
[email protected], 8143260297
// get server information
echo $_SERVER['SERVER_NAME'];
?>

Using constants
 Constants in PHP are identifiers or names that remain constant throughout the program and
cannot be changed during the execution.
 Once a constant is defined, it cannot be undefined or redefined and always written in upper
case.
 PHP constants can be defined by 2 ways:
1) Using define() function
2) Using const keyword

Using define() Function


The define() function in PHP is used to create a constant as shown below:
Syntax
define( 'CONSTANT_NAME', value, case_insensitive )
where
name: The name of the constant.
value: The value to be stored in the constant.
case_insensitive: Defines whether a constant is case insensitive. By default this value is
False, i.e., case sensitive.

Example
<?php
// This creates a case-sensitive constant
define("WELCOME", "KHIT");
echo WELCOME . "\n";

// This creates a case-insensitive constant


define("HELLO", "KHIT", true);
echo hello;
?>

Using const keyword


The const keyword is another way to define constants but is typically used inside classes and
functions. The key difference from define() is that constants defined using const cannot be case-
insensitive.
Syntax
const CONSTANT_NAME = value;

Example
<?php
const SITE_NAME = 'KHIT';
echo SITE_NAME;
?>

Page 7
Dr. Vamshi Krishna K
Associate Professor, Dept. of CSE, KHIT, Guntur
[email protected], 8143260297
Difference between Constants and Variables
Feature Constants Variables

Syntax No dollar sign ($) Starts with a dollar sign ($)

Value Immutable Mutable

Case Sensitivity Case-sensitive (default) Case-sensitive

Global Scope Always global Scope can vary (local or global)

Declaration Methods define() or const Use of $ symbol

Data types
PHP is a loosely typed language, which means variables do not need to be declared with a specific
data type. PHP allows eight different types of data types. PHP supports the following data types:
1) Predefined Data Types
Integer:
 Integers hold only whole numbers including positive and negative numbers, i.e.,
numbers without fractional part or decimal point.
 They can be decimal (base 10), octal (base 8), or hexadecimal (base 16). The
default base is decimal (base 10). The octal integers can be declared with leading
0 and the hexadecimal can be declared with leading 0x.
 The range of integers must lie between -2^31 to 2^31.
Example
<?php
// decimal base integers
$deci1 = 50;
$deci2 = 654;

// octal base integers


$octal1 = 07;

// hexadecimal base integers


$octal = 0x45;

$sum = $deci1 + $deci2;


echo $sum;
echo "\n\n";

//returns data type and value


var_dump($sum)
?>

Page 8
Dr. Vamshi Krishna K
Associate Professor, Dept. of CSE, KHIT, Guntur
[email protected], 8143260297
Float (Double): Can hold numbers containing fractional or decimal parts including positive and
negative numbers or a number in exponential form.
Example
<?php
$val1 = 50.85;
$val2 = 654.26;
$sum = $val1 + $val2;
echo $sum;
echo "\n\n";
//returns data type and value
var_dump($sum)
?>

String: Hold letters or any alphabets, even numbers are included. These are written within double
quotes during declaration. The strings can also be written within single quotes, but they will be
treated differently while printing variables.
Example
<?php
$name = "Krishna";
echo "The name of the Geek is $name \n";
echo 'The name of the geek is $name ';
echo "\n\n";
//returns data type, size and value
var_dump($name)
?>

Boolean: Boolean data types are used in conditional testing. Hold only two values, either TRUE(1)
or FALSE(0). Successful events will return true and unsuccessful events return false.
Example
<?php
if(TRUE)
echo "This condition is TRUE";
if(FALSE)
echo "This condition is not TRUE";
?>

2) User-Defined (compound) Data Types


Array: Array is a compound data type that can store multiple values of the same data type.
Example
<?php
$intArray = array( 10, 20 , 30);
echo "First Element: $intArray[0]\n";
echo "Second Element: $intArray[1]\n";
echo "Third Element: $intArray[2]\n\n";
//returns data type and value
var_dump($intArray);
?>

Page 9
Dr. Vamshi Krishna K
Associate Professor, Dept. of CSE, KHIT, Guntur
[email protected], 8143260297
Objects: Objects are defined as instances of user-defined classes that can hold both values and
functions and information for data processing specific to the class. When the objects are created,
they inherit all the properties and behaviours from the class, having different values for all the
properties.
Example
<?php
class gfg {
public $message;

function __construct($message) {
$this->message = $message;
}

function msg() {
return "This is an example of " . $this->message . "!";
}
}
$newObj = new gfg("Object Data Type");
echo $newObj->msg();
?>

3) Special Data Types


Null: These are special types of variables that can hold only one value. If a variable is created
without a value or no value, it is automatically assigned a value of NULL. It is written in capital
letters.
Example
<?php
$nm = NULL;
echo $nm; // this will return no output
// return data type
var_dump($nm);
?>

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.

Arithmetic Operators: The arithmetic operators are used to perform simple mathematical
operations like addition, subtraction, multiplication, etc.
Operator Name Syntax Operation

+ Addition $x + $y Sum the operands

– Subtraction $x – $y Differences the operands

* Multiplication $x * $y Product of the operands

Page 10
Dr. Vamshi Krishna K
Associate Professor, Dept. of CSE, KHIT, Guntur
[email protected], 8143260297

Operator Name Syntax Operation

/ Division $x / $y The quotient of the operands

** Exponentiation $x ** $y $x raised to the power $y

% Modulus $x % $y The remainder of the operands

Example
<?php
// Define two numbers
$x = 10;
$y = 3;

// Addition
echo "Addition: " . ($x + $y) . "\n";

// Subtraction
echo "Subtraction: " . ($x - $y) . "\n";

// Multiplication
echo "Multiplication: " . ($x * $y) . "\n";

// Division
echo "Division: " . ($x / $y) . "\n";

// Exponentiation
echo "Exponentiation: " . ($x ** $y) . "\n";

// Modulus
echo "Modulus: " . ($x % $y) . "\n";
?>

Logical: You can use Logical operators in PHP to perform logical operations on multiple expressions
together. Logical operators always return Boolean values, either true or false. Logical operators are
commonly used with conditional statements and loops to return decisions according to the Boolean
conditions.
Operator Name Syntax Operation

True if both the operands


and Logical AND $x and $y
are true else false

or Logical OR $x or $y True if either of the

Page 11
Dr. Vamshi Krishna K
Associate Professor, Dept. of CSE, KHIT, Guntur
[email protected], 8143260297

Operator Name Syntax Operation

operands is true else false

True if either of the


xor Logical XOR $x xor $y operands is true and false
if both are true

True if both the operands


&& Logical AND $x && $y
are true else false

True if either of the


|| Logical OR $x || $y
operands is true else false

! Logical NOT !$x True if $x is false

Comparison Operators: These operators are used to compare two elements and outputs the result
in boolean form.
Operator Name Syntax Operation

Returns True if both the


== Equal To $x == $y
operands are equal

Returns True if both the


!= Not Equal To $x != $y
operands are not equal

Returns True if both the


<> Not Equal To $x <> $y
operands are unequal

Returns True if both the


=== Identical $x === $y operands are equal and
are of the same type

Returns True if both the


!== Not Identical $x == $y operands are unequal and
are of different types

Page 12
Dr. Vamshi Krishna K
Associate Professor, Dept. of CSE, KHIT, Guntur
[email protected], 8143260297

Operator Name Syntax Operation

Returns True if $x is less


< Less Than $x < $y
than $y

Returns True if $x is
> Greater Than $x > $y
greater than $y

Less Than or Equal Returns True if $x is less


<= $x <= $y
To than or equal to $y

Returns True if $x is
Greater Than or
>= $x >= $y greater than or equal to
Equal To
$y

Conditional or Ternary Operators: These operators are used to compare two values and take
either of the results simultaneously, depending on whether the outcome is TRUE or FALSE. These
are also used as a shorthand notation for if…else statement that we will read in the article on
decision making.
Syntax
$var = (condition)? value1 : value2;

Assignment Operators: These operators are used to assign values to different variables, with or
without mid-operations.
Operator Name Syntax Operation

Operand on the left


obtains the value of
= Assign $x = $y
the operand on the
right

Simple Addition
+= Add then Assign $x += $y
same as $x = $x + $y

Subtract then Simple subtraction


-= $x -= $y
Assign same as $x = $x – $y

Multiply then Simple product same


*= $x *= $y
Assign as $x = $x * $y

Divide then Simple division same


/= $x /= $y
Assign as $x = $x / $y

Page 13
Dr. Vamshi Krishna K
Associate Professor, Dept. of CSE, KHIT, Guntur
[email protected], 8143260297

Operator Name Syntax Operation

(quotient)

Divide then
Assign Simple division same
%= $x %= $y
(remainder) as $x = $x % $y

Assignment Operators: These operators are used to assign values to different variables, with or
without mid-operations.

Operator Name Syntax Operation

Operand on the left obtains


= Assign $x = $y the value of the operand on
the right

Simple Addition same as


+= Add then Assign $x += $y
$x = $x + $y

Simple subtraction same as


-= Subtract then Assign $x -= $y
$x = $x – $y

Simple product same as $x


*= Multiply then Assign $x *= $y
= $x * $y

Divide then Assign Simple division same as $x


/= $x /= $y
(quotient) = $x / $y

Divide then Assign


Simple division same as $x
%= (remainder) $x %= $y
= $x % $y

Increment/Decrement Operators: These are called the unary operators as they work on single
operands. These are used to increment or decrement values.
Operator Name Syntax Operation

++ Pre-Increment ++$x First increments $x by one,

Page 14
Dr. Vamshi Krishna K
Associate Professor, Dept. of CSE, KHIT, Guntur
[email protected], 8143260297

Operator Name Syntax Operation

then return $x

First decrements $x by one,


— Pre-Decrement –$x
then return $x

First returns $x, then


++ Post-Increment $x++
increment it by one

First returns $x, then


— Post-Decrement $x–
decrement it by one

Controlling program flow


Conditional statements
1) if Statement: This statement allows us to set a condition. On being TRUE, the following block of
code enclosed within the if clause will be executed.
Syntax:
if (condition){
// if TRUE then execute this code
}
Example
<?php
$x = 12;

if ($x > 0) {
echo "The number is positive";
}
?>

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
}

Page 15
Dr. Vamshi Krishna K
Associate Professor, Dept. of CSE, KHIT, Guntur
[email protected], 8143260297
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";
}
?>

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:
if (condition) {
// if TRUE then execute this code
}
elseif {
// if TRUE then execute this code
}
elseif {
// if TRUE then execute this code
}
else {
// if FALSE then execute this code
}
Example
<?php
$x = "August";

if ($x == "January") {
echo "Happy Republic Day";
}

elseif ($x == "August") {


echo "Happy Independence Day!!!";

Page 16
Dr. Vamshi Krishna K
Associate Professor, Dept. of CSE, KHIT, Guntur
[email protected], 8143260297
}

else{
echo "Nothing to show";
}
?>

4) 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.
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":

Page 17
Dr. Vamshi Krishna K
Associate Professor, Dept. of CSE, KHIT, Guntur
[email protected], 8143260297
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":
echo "Its June";
break;
case "July":
echo "Its July";
break;
case "August":
echo "Its August";
break;
case "September":
echo "Its September";
break;
case "October":
echo "Its October";
break;
case "November":
echo "Its November";
break;
case "December":
echo "Its December";
break;
default:
echo "Doesn't exist";
}
?>

Control statements: PHP Loops are used to repeat a block of code multiple times based on a given
condition.
1) for: PHP for loop is used when you know exactly how many times you want to iterate through a
block of code. It consists of three expressions
Synatx
for ( Initialization; Condition; Increment/Decrement ) {
// Code to be executed
}

Page 18
Dr. Vamshi Krishna K
Associate Professor, Dept. of CSE, KHIT, Guntur
[email protected], 8143260297
Example
<?php

// Code to illustrate for loop


for ($num = 1; $num <= 5; $num += 1) {
echo $num . " ";
}
?>

2) while: The while loop is also an entry control loop like for loops. It first checks the condition at
the start of the loop and if its true then it enters into the loop and executes the block of statements,
and goes on executing it as long as the condition holds true.
Syntax
while ( condition ) {
// Code is executed
}
Example
<?php
$num = 1;
while ($num <= 5) {
echo $num . " ";
$num++;
}
?>

3) do while: The do-while loop is an exit control loop which means, it first enters the loop,
executes the statements, and then checks the condition. Therefore, a statement is executed at least
once using the do…while loop. After executing once, the program is executed as long as the
condition holds true.
Syntax
do {
// Code is executed
} while ( condition );

Example
<?php

$num = 1;

do {
echo $num . " ";
$num++;
} while ($num <= 5);
?>

4) foreach: This foreach loop is used to iterate over arrays. For every counter of loop, an array
element is assigned and the next counter is shifted to the next element.
Syntax
foreach ( $array as $value ) {

Page 19
Dr. Vamshi Krishna K
Associate Professor, Dept. of CSE, KHIT, Guntur
[email protected], 8143260297
// Code to be executed
}

// or

foreach ( $array as $key => $value ) {


// Code to be executed
}

Example
<?php

// foreach loop over an array


$arr = array (10, 20, 30, 40, 50, 60);

foreach ($arr as $val) {


echo $val . " ";
}

echo "\n";

// foreach loop over an array with keys


$ages = array(
"John" => 25,
"Alice" => 30,
"Bob" => 22
);

foreach ($ages as $name => $age) {


echo $name . " => " . $age . "\n";
}
?>

Arrays
Arrays in PHP are a type of data structure that allows us to store multiple elements of similar or
different data types under a single variable thereby saving us the effort of creating a different
variable for every data. The arrays are helpful to create a list of elements of similar types, which
can be accessed using their index or key.
There are 3 types of array in PHP.
1. Indexed Array
2. Associative Array
3. Multidimensional Array

Indexed array:
PHP index is represented by number which starts from 0. We can store number, string and object in
the PHP array. All PHP array elements are assigned to an index number by default.
Example
<?php
$season=array("summer","winter","spring","autumn");

Page 20
Dr. Vamshi Krishna K
Associate Professor, Dept. of CSE, KHIT, Guntur
[email protected], 8143260297
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
?>

Associative array:
We can associate name with each array elements in PHP using => symbol.
Example
<?php
$salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
echo "John salary: ".$salary["John"]."<br/>";
echo "Kartik salary: ".$salary["Kartik"]."<br/>";
?>

Multidimensional array:
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.
Example
<?php
$emp = array
(
array(1,"sonoo",400000),
array(2,"john",500000),
array(3,"rahul",300000)
);

for ($row = 0; $row < 3; $row++) {


for ($col = 0; $col < 3; $col++) {
echo $emp[$row][$col]." ";
}
echo "<br/>";
}
?>

Functions
A function is a block of code written in a program to perform some specific task. PHP provides us
with two major types of functions:
1) Built-in functions: PHP provides us with huge collection of built-in library functions.
These functions are already coded and stored in form of functions. To use those we just
need to call them as per our requirement like, var_dump, fopen(), print_r(), gettype() and so
on.
2) User Defined Functions: Apart from the built-in functions, PHP allows us to create our
own customised functions called the user-defined functions. Using this we can create our
own packages of code and use it wherever necessary by simply calling it.

Features
1) Reusability
2) Easier error detection
3) Easily maintained

Page 21
Dr. Vamshi Krishna K
Associate Professor, Dept. of CSE, KHIT, Guntur
[email protected], 8143260297
Syntax
function function_name(){
executable code;
}

Example
<?php
function funckhit()
{
echo "This is KHIT";
}

// Calling the function


funcGeek();
?>

Parameter passing to Functions


PHP allows us two ways in which an argument can be passed into a function:
 Pass by Value: On passing arguments using pass by value, the value of the argument gets
changed within a function, but the original value outside the function remains unchanged. That
means a duplicate of the original value is passed as an argument.
 Pass by Reference: On passing arguments as pass by reference, the original value is passed.
Therefore, the original value gets altered. In pass by reference we actually pass the address of
the value, where it is stored using ampersand sign(&).

Example
<?php

// pass by value
function valkhit($num) {
$num += 2;
return $num;
}

// pass by reference
function refkhit(&$num) {
$num += 10;
return $num;
}

$n = 10;
valkhit($n);
echo "The original value is still $n \n";
refkhit($n);
echo "The original value changes to $n";
?>

Page 22

You might also like