KEMBAR78
Unit IV PHP Oss | PDF | Php | Variable (Computer Science)
0% found this document useful (0 votes)
44 views19 pages

Unit IV PHP Oss

Uploaded by

then mozhi
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)
44 views19 pages

Unit IV PHP Oss

Uploaded by

then mozhi
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/ 19

MARUDHAR KESARI JAIN COLLEGE FOR WOMEN, VANIYAMBADI

PG DEPARTMENT OF COMPUTER APPLICATIONS

Class : III BCA

Subject Name : Open Source Software

Subject Code : CCA61

SYLLABUS

UNIT IV: PHP

PHP Introduction – General Syntactic Characteristics – PHP Scripting –


Commenting your code – Primitives, Operations and Expressions – PHP
Variables – Operations and Expressions Control Statement – Array – Functions
– Basic Form Processing – File and Folder Access – Cooking – Sessions –
Database Access with PHO.
PHP Introduction

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. PHP is a server side scripting language that is also an interpreted language. It is
basically used for developing software applications that have dynamic content and require constant
interactions with databases. It is an open source language making it one of the most sought out
platforms for developers and companies.

Features and Advantages


 The performance of the scripts written in php is much better than those written in other
languages like JSP and ASP.
 Being open source, we can develop and maintain our applications without incurring any
cost.
 PHP is a platform independent language, i.e., it can run on any OS without any problem
 PHP code can also be embedded into HTML tags and script.

Commenting your code


A comment is a piece of code that is not executed by the compiler rather it is there just for the
human reader to read. Comments in general are used to explain the code better and improve the
readability of the code.

There are multiple types of comments

Single Line Comments

Single-line comments are used to provide short explanations or points related to the code.

<? //This is a comment ?>

Multi-line comments

Multiline comments are used to provide more detailed explanations about the code whenever
necessary. This system of commenting is same as the system of commenting in C

<? /*This is a multiline comment */ ?>

The Assignment Operator


You have seen the assignment operator in use each time a variable was declared in an example; the
assignment operator consists of the single character: =. The assignment operator takes the value of the right-
side operand and assigns it to the left-side operand:

$name = "jimbo";
Operations and Expressions
The variable $name now contains the string "jimbo". This construct is also an expression. Although it might
seem at first glance that the assignment operator simply changes the variable $name without producing a value,
in fact, a statement that uses the assignment operator always resolves to a copy of the value of the right operand.
Thus

echo $name = "jimbo";

prints the string "jimbo" to the browser while it also assigns the value "jimbo" to the $name variable.
Arithmetic Operators
The arithmetic operators do exactly what you would expect—they perform arithmetic operations. Table 5.2 lists
these operators along with examples of their usage and results.

Table 5.2. Arithmetic Operators


Operator Name Example Sample Result

+ Addition 10+3 13

− Subtraction 10−3 7

/ Division 10/3 3.3333333333333

* Multiplication 10*3 30

% Modulus 10%3 1

The addition operator adds the right-side operand to the left-side operand. The subtraction operator subtracts
the right-side operand from the left-side operand. The division operator divides the left-side operand by the right-
side operand. The multiplication operator multiplies the left-side operand by the right-side operand. The modulus
operator returns the remainder of the left-side operand divided by the right-side operand.

The Concatenation Operator


The concatenation operator is represented by a single period (.). Treating both operands as strings, this operator
appends the right-side operand to the left-side operand. So

"hello"." world"

returns
"hello world"

Note that the resulting space between the words occurs because there is a leading space in the second operand
(" world" instead of "world"). The concatenation operator literally smashes together two strings without
adding any padding. So, if you tried to concatenate two strings without leading or trailing spaces, such as

"hello"."world"

you would get this as your result:

"helloworld"

Regardless of the data types of the operands used with the concatenation operator, they are treated as strings,
and the result will always be of the string type. You will encounter concatenation frequently throughout this book
when the results of an expression of some kind must be combined with a string, as in

$cm = 212;

echo "the width is ".($cm/100)." meters";

Combined Assignment Operators


Although there is only one true assignment operator, PHP provides a number of combination operators that
transform the left-side operand and return a result, while also modifying the original value of the variable. As a
rule, operators use operands but do not change their original values, but combined assignment operators break
this rule. A combined assignment operator consists of a standard operator symbol followed by an equal sign.
Combination assignment operators save you the trouble of using two operators in two different steps within your
script. For example, if you have a variable with a value of 4, and you want to increase this value to 4 more, you
might see:

$x = 4;

$x = $x + 4; // $x now equals 8
However, you can also use a combination assignment operator (+=) to add and return the new value, as shown
here:

$x = 4;

$x += 4; // $x now equals 8

Each arithmetic operator, as well as the concatenation operator, also has a corresponding combination
assignment operator. Table 5.3 lists these new operators and shows an example of their usage.

Table 5.3. Some Combined Assignment Operators


Operator Example Equivalent To

+= $x += 5 $x = $x + 5

−= $x −= 5 $x = $x − 5

/= $x /= 5 $x = $x / 5

*= $x *= 5 $x = $x * 5

%= $x %= 5 $x = $x % 5

.= $x .= " test" $x = $x." test"

Each of the examples in Table 5.3 transforms the value of $x using the value of the right-side operand.
Subsequent uses of $x will refer to the new value. For example

$x = 4;

$x += 4; // $x now equals 8

$x += 4; // $x now equals 12

$x -= 3; // $x now equals 9

These operators will be used throughout the scripts in the book. You will frequently see the combined
concatenation assignment operator when you begin to create dynamic text; looping through a script and adding
content to a string, such as dynamically building the HTML code to represent a table, is a prime example of the
use of a combined assignment operator.

Automatically Incrementing and Decrementing an Integer Variable


When coding in PHP, you will often find it necessary to increment or decrement a variable that is an integer type.
You will usually need to do this when you are counting the iterations of a loop. You have already learned two
ways of doing this—either by incrementing the value of $x using the addition operator

$x = $x + 1; // $x is incremented by 1

or by using a combined assignment operator

$x += 1; // $x is incremented by 1

In both cases, the new value is assigned to $x. Because expressions of this kind are common, PHP provides
some special operators that allow you to add or subtract the integer constant 1 from an integer variable, assigning
the result to the variable itself. These are known as the post-increment and post-decrement operators. The post-
increment operator consists of two plus symbols appended to a variable name:

$x++; // $x is incremented by 1

This expression increments the value represented by the variable $x by one. Using two minus symbols in the
same way will decrement the variable:

$x--; // $x is decremented by 1

If you use the post-increment or post-decrement operators in conjunction with a conditional operator, the operand
will be modified only after the first operation has finished:

$x = 3;

$y = $x++ + 3;

In this instance, $y first becomes 6 (the result of 3 + 3) and then $x is incremented.


In some circumstances, you might want to increment or decrement a variable in a test expression before the test
is carried out. PHP provides the pre-increment and pre-decrement operators for this purpose. These operators
behave in the same way as the post-increment and post-decrement operators, but they are written with the plus
or minus symbols preceding the variable:
++$x; // $x is incremented by 1

--$x; // $x is decremented by 1

If these operators are used as part of a test expression, incrementing occurs before the test is carried out. For
example, in the next fragment, $x is incremented before it is tested against 4.

$x = 3;

++$x < 4; // false

The test expression returns false because 4 is not smaller than 4.


Comparison Operators
Comparison operators perform comparative tests using their operands and return the Boolean value true if the
test is successful or false if the test fails. This type of expression is useful when using control structures in your
scripts, such as if and while statements. This book covers if and whilestatements in Chapter 6, “Flow
Control Functions in PHP.”
For example, to test whether the value contained in $x is smaller than 5, you can use the less-than operator as
part of your expression:

$x < 5

If $x contains the value 3, this expression will have the value true. If $x contains 7, the expression resolves
to false.
Table 5.4 lists the comparison operators.

Table 5.4. Comparison Operators


Operator Name Returns True If... Example Result
($xIs 4)

== Equivalence Left is equivalent to right $x == 5 false

!= Non-equivalence Left is not equivalent to right $x != 5 true

=== Identical Left is equivalent to right and they are the $x === 4 true
same type
Operator Name Returns True If... Example Result
($xIs 4)

Non-equivalence Left is equivalent to right but they are not the $x === "4" false
same type

> Greater than Left is greater than right $x > 4 false

>= Greater than or equal Left is greater than or equal to right $x >= 4 true
to

< Less than Left is less than right $x < 4 false

<= Less than or equal to Left is less than or equal to right $x <= 4 true

These operators are most commonly used with integers or doubles, although the equivalence operator is also
used to compare strings. Be very sure to understand the difference between the == and = operators.
The == operator tests equivalence, whereas the = operator assigns value. Also, remember that === tests
equivalence with regards to both value and type.
Creating Complex Test Expressions with the Logical Operators
Logical operators test combinations of Boolean values. For example, the or operator, which is indicated by two
pipe characters (||) or simply the word or, returns the Boolean value true if either the left or the right operand
is true:

true || false

This expression returns true.


The and operator, which is indicated by two ampersand characters (&&) or simply the word and, returns the
Boolean value true only if both the left and right operands are true:

true&& false

This expression returns the Boolean value false. It’s unlikely that you will use a logical operator to test Boolean
constants because it makes more sense to test two or more expressions that resolve to a Boolean. For example

($x > 2) && ($x < 15)


returns the Boolean value true if $x contains a value that is greater than 2 and smaller than 15. Parentheses
are used when comparing expressions to make the code easier to read and to indicate the precedence of
expression evaluation. Table 5.5 lists the logical operators.

Table 5.5. Logical Operators


Operator Name Returns True If... Example Result

|| Or Left or right is true true || false true

or Or Left or right is true true or false true

xor Xor Left or right is true but not both true xor true false

&& And Left and right are true true && false false

and And Left and right are true true and false false

! Not The single operand is not true ! true false

Expressions
Expressions are the most important building blocks of PHP. In PHP, almost anything you write is
an expression. The simplest yet most accurate way to define an expression is "anything that has a
value".

The most basic forms of expressions are constants and variables. When you type "$a = 5", you're
assigning '5' into$a. '5', obviously, has the value 5, or in other words '5' is an expression with the
value of 5 (in this case, '5' is an integer constant).

After this assignment, you'd expect $a's value to be 5 as well, so if you wrote $b = $a, you'd expect
it to behave just as if you wrote $b = 5. In other words, $a is an expression with the value of 5 as
well. If everything works right, this is exactly what will happen.

Slightly more complex examples for expressions are functions. For instance, consider the
following function:

<?php
function foo ()
{
return 5;
}
?>
Assuming you're familiar with the concept of functions (if you're not, take a look at the chapter
about functions), you'd assume that typing $c = foo() is essentially just like writing $c = 5, and
you're right. Functions are expressions with the value of their return value. Since foo() returns 5,
the value of the expression 'foo()' is 5. Usually functions don't just return a static value but compute
something.

PHP Variables
Variables in a program are used to store some values or data that can be used later in a program.
The variables are also like containers that store character values, numeric values, memory
addresses, and strings. PHP has its own way of declaring and storing variables.
There are few rules, that needs to be followed and facts that need to be kept in mind while dealing
with variables in PHP:
 Any variables declared in PHP must begin with a dollar sign ($), followed by the variable
name.
 A variable can have long descriptive names (like $factorial, $even_nos) or short names (like
$n or $f or $x)
 A variable name can only contain alphanumeric characters and underscores (i.e., ‘a-z’, ‘A-
Z’, ‘0-9 and ‘_’) in their name. Even it cannot start with a number.
 A constant is used as a variable for a simple value that cannot be changed. It is also case-
sensitive.
 Assignment of variables is done with the assignment operator, “equal to (=)”. The variable
names are on the left of equal and the expression or values are to the right of the assignment
operator ‘=’.
 One must keep in mind that variable names in PHP names must start with a letter or
underscore and no numbers.
 PHP is a loosely typed language, and we do not require to declare the data types of variables,
rather PHP assumes it automatically by analyzing the values. The same happens while
conversion. No variables are declared before they are used. It automatically converts types
from one type to another whenever required.
 PHP variables are case-sensitive, i.e., $sum and $SUM are treated differently.

Example
<?php
$var = 'Bob';
$Var = 'Joe';
echo "$var, $Var"; // outputs "Bob, Joe"

$4site = 'not yet'; // invalid; starts with a number


$_4site = 'not yet'; // valid; starts with an underscore
$täyte = 'mansikka'; // valid; 'ä' is (Extended) ASCII 228.
?>

Control –statement
Control statements are a basic component of all modern-day programming languages like PHP,
Java, Python, Go, Ruby, NodeJS. These control statements allow software developers and
architects to decide how the software or program they develop will behave under different
conditions. For instance, on an e-commerce platform, the developers would want the same system
to behave differently for different user roles like buyers as well as sellers. Such kind of
distinguished behaviors can only be achieved with control statements.

Different Control Statement in PHP


Like all other languages, PHP provides a few control statements enabling developers to develop
different logic to execute in different conditions. PHP core includes the control statements:
 if
 if.else
 if.else..if
 Switch statement
Let us look at each of these control statements with details and understand their implementation
through examples.

1. The IF Statement in PHP


The IF statement in PHP is the most simplified control statement of the language.The IF condition
works on a Boolean value which is evaluated based on a certain condition and it is used to execute
certain lines of code only if a condition is met or is true. The condition provided to the IF
statement is first to evaluate, depending on the evaluation a False or True value is generated and
on basis of it the code if the IF condition block is either executed or skipped in the program flow.
Let’s walk through the syntax of if statement to understand it better:
if (my_condition) {
code to execute if the condition supplied is true;
}
As shown above, the if statement requires a condition in the () round brackets which should be
evaluated. In the curly braces, {} we supply the code spec which should be executed.
et’s see an example below:
Code:
<?php
$a=20;
$b=10;
if($a>$b)
{
echo "A is greater than B";
}
?>
Output:

2. The IF-ELSE Statement in PHP


As mentioned before, the IF statement provides a very basic program control. The IF-ELSE
statement adds further complexity to the IF statement by defining 2 blocks of code; one to be
executed when the condition stands true and other when the condition evaluates to false. Naturally,
since the condition can either evaluate to true or false either the code block in IF would execute or
the code block under ELSE would execute. Under no circumstances, both blocks will execute
parallel.
Let’s review it’s syntax below:
if (condition top evaluate) {
code to executed if the condition supplied is true;
}
else
{
code to execute if the condition supplied is false;
}
Let’s understand it’s implementation with an example:
Code:
<?php
$a=20;
$b=10;
if($a>$b)
{
echo "A is greater than B";
}
else
{
echo "B is greater than B";
}
?>
Output:

Now, when the values of $a and $b are switched in the above code as shown below:
Code:
<?php
$a=10;
$b=20;
if($a>$b)
{
echo "A is greater than B";
}
else
{
echo "B is greater than A";
}
?>
Output:

3. The IF – ELSE–IF Statement in PHP


Sometimes a need may arise to use multiple if conditions together, in such cases we can use a
combination of multiple if-else statements. We can combine several if-else statements to work
together as long as our requirement is met.
The syntax of if-else if combination statement would be as follows:
If (condition1)
{
Code to execute;
}
elseIf(condition2)
{
Code to execute if condition 2 is met;
}
Else
{
Code to execute if condition1 and condition2 are not met;
}
Let’s understand this better with an example:
Code:
<?php
$t = date("H"); //collecting the date from server
echo "The time is " . $t;
echo ", and we will show the following message:";
echo "\n";
if ($t < "10") { //condition 1
echo "Hello! I hope you have a good morning!";
} elseif ($t < "20") { //condition 2
echo "Hello! I hope you have a good day!";
} else {
echo "Hello! I hope you have a good night!";
}
?>
Output:
4. Switch Statement in PHP
The Switch Statement or generally known as a switch loop is a very efficient way to work with
multiple conditions simultaneously. It allows us to achieve the same functionality as if-else if and
else does but can be achieved with lesser lines of code.
Syntax:
switch (condition) {
case value1:
code to be executed if n=label1;
break;
case value 2:
code to be executed if n=label2;
break;
case value 3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}
The Switch statement first evaluates the “condition” and then executes the code in the block with
corresponding label value. If none of the label values match the condition, it executes the code in
the default block.
Now let’s understand the flow of the switch statement with the below practical example:
Code:
<?php
$myfavsport = "cricket";
switch ($myfavsport) {
case "cricket":
echo "Your favorite sport is cricket!";
break;
case " football":
echo "Your favorite sport is football!";
break;
case "throwball":
echo "Your favorite sport is throwball!";
break;
default:
echo "Your favorite sport is neither cricket, football or
throwball!";
}
?>
Output:

Arrays
Arrays in PHP, provides you with an outline for the creation of arrays in PHP. An array is a
collection of similar datatypes. An array stores multiple values in a single variable. Why there is a
need for an array when the work of storing a value can be done by variable also? The answer is
because to store values of limited data like count of numbers 5 is possible, but when count increases
to say 100 or 200 we need to store 100 values in 100 variables which is a bit difficult thus we store
it in an array. This is why arrays are used.

How to Create Arrays in PHP?


Syntax:
variablename = array();
OR
variablename[i] = value;,
Where variable name is the name of the variable i is the key or the index value is the element value.
Example to Create an Array
$colors = array(“Red”,”Green”,”Blue”);

To calculate the length of array we use the count keyword.


$length = count($colors); // output is 3

Each value in the array is termed as an element of the array. The array index begins with 0. And
the index of the last element in an array is the total length of the array minus 1.
In the given example above, the index of Red is 0, Green is 1 and that of Blue is 2. It really becomes
easier to access the array with the help of the index or a key. To get the value at each index of an
array we loop through the given array. To loop the array we use a foreach loop or for a loop.

Types of Arrays in PHP


There are three types of arrays that you can create. These are:
 Indexed array — An array with a numeric key.
 Associative array — An array where each key has its own specific value.
 Multidimensional array — An array containing one or more arrays within itself.

Indexed Arrays
An indexed or numeric array stores each array element with a numeric index. The following
examples shows two ways of creating an indexed array, the easiest way is:

Example
<?php
// Define an indexed array
$colors = array("Red", "Green", "Blue");
?>
Note: In an indexed or numeric array, the indexes are automatically assigned and start with 0, and
the values can be any data type.
This is equivalent to the following example, in which indexes are assigned manually:

Example
<?php
$colors[0] = "Red";
$colors[1] = "Green";
$colors[2] = "Blue";
?>

Associative Arrays
In an associative array, the keys assigned to values can be arbitrary and user defined strings. In the
following example the array uses keys instead of index numbers:

Example
<?php
// Define an associative array
$ages = array("Peter"=>22, "Clark"=>32, "John"=>28);
?>
The following example is equivalent to the previous example, but shows a different way of creating
associative arrays:

Example
<?php
$ages["Peter"] = "22";
$ages["Clark"] = "32";
$ages["John"] = "28";
?>

Multidimensional Arrays
The multidimensional array is an array in which each element can also be an array and each
element in the sub-array can be an array or further contain array within itself and so on. An example
of a multidimensional array will look something like this:

Example
<?php
// Define a multidimensional array
$contacts = array(
array(
"name" => "Peter Parker",
"email" => "peterparker@mail.com",
),
array(
"name" => "Clark Kent",
"email" => "clarkkent@mail.com",
),
array(
"name" => "Harry Potter",
"email" => "harrypotter@mail.com",
)
);
// Access nested value
echo "Peter Parker's Email-id is: " . $contacts[0]["email"];
?>

Functions
IN PHP, many functions are used such as built-in functions and user-defined functions. Each and
every function has its own functionality and properties. A function is a set of statements written in
the program that can be used multiple times in the code anywhere needed. A function call is
required to execute the statements written inside the function. It is a piece of code that takes one
or more inputs as a parameter and processes it and returns a value. Programmers simply have to
create a function and then call that function in the program wherever required.

Types of Functions in PHP


In PHP, mainly two functions are used by the programmers. They are:

1. User-Defined
These functions are used when the developer or programmer has to execute their own logic of
code. These functions are defined using the keyword function and inside the function, a set of
statements will be written to execute it when a function call occurs. The function call can be made
by just simply calling the function like functionname(), and the function will get executed.

2. Built-in
These functions provide us with built-in library functions. PHP provides these functions in the
installation package itself which makes this language more powerful and useful. To use the
properties of the function we just need to call the function wherever required to fetch the desired
result.

There are many built-in functions used in PHP such as Date, Numeric, String, etc.

String Functions: These functions have a predefined functionality in PHP to work with strings.
PHP has various string functions such as strpos(), strncmp(), strrev(), strlen(),
Date Function: These functions are predefined functionality in PHP where the format is a UNIX
date and time which is a human-readable format.

Numeric Functions: These functions have their own predefined logic provided by PHP which is
used for numeric operations. It will return the result either in Boolean form or in the numeric form.
Some of the numeric functions include is_number(), number_format(), round() ,etc.

How Functions are Used in PHP?


As we discussed earlier, in PHP we have two functions i.e. built-in and user-defined. Let’s
understand more about these functions:
Example #1
For String Functions
Code:
<!DOCTYPE html>
<html>
<body>
<?php
print_r(str_split("Hi This is a test sample"));
?>
</body>
</html>
Output:

The explanation for the above program: In the above example, the string that we passed inside
the function str_split(), splits the string on to a single character and produces the output.
Example #2
Code:
<!DOCTYPE html>
<html>
<body>
<?php
echo strcmp("Hi this is test","Hi this is test");
?>
<p>If this function returns 0, the two strings are same.</p>
</body>
</html>
Output:
The explanation for the above program: In the above example, the function strcmp () will
compare the strings and if the strings are the same it will return zero and if the strings are not equal
then it will return some other number.

You might also like