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

PHP_unit_II_MB

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)
6 views

PHP_unit_II_MB

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/ 80

UNIT II

Exploring PHP-PHP and HTML text - coding building blocks.PHP


decision making-Expressions - Operator Concepts - Conditionals-
Looping. Functions - calling functions - defining functions- Object-
Oriented Programming. Arrays: Array fundamentals. Database basics:
Data base design-Structured Query Language.

Unit II

PHP and HTML Text

Text Output

<html>

<head>

<title>Hello World</title>

</head>

<body>

<?php

// A single line comment could say that we are going to

// print hello world.

/* This is how to do a

multiline comment and could be used to comment out a block

of code */

echo "Hello world!<br />";

echo "Goodbye.<br />";

?>

</body>

</html>
Coding Building Blocks

To write programs in PHP that do something useful, you’ll need to


understand blocks of reusable code called functions or methods.

Variables

In PHP, you define a variable with the following form:

$variable_name = value;

The dollar sign ($) must always fill the first space of your variable.
The first character after the dollar sign must be either a letter or an
underscore. It can’t under any circumstances be a number;
otherwise, your code won’t execute.

PHP variables may be composed only of alphanumeric characters


and underscores; for example, a-z, A-Z, 0-9, and _.

• Variables in PHP are case-sensitive. This means that


$variable_name and

$Variable_Name are different.

• Variables with more than one word can be separated with


underscores to make

them easier to read; for example, $test_variable.

• Variables can be assigned values using the equals sign (=).

• Always end with a semicolon (;) to complete the assignment of the


variable.

<?php

$age = 30;

?>

Reading a variable’s value

Variable types

PHP automatically picks a data variable based on the value assigned.


These data types include strings, numbers, and more complex elements,
such as arrays.
In situations where a specific type of data is required, such as the
mathematical division operation, PHP attempts to convert the data types
automatically. If you have a string with a single “2,” it will be converted
to an integer value of 2.

Variable scope

PHP provides separate storage of variables within each function. This


separate storage space means that the scope, or where a variable’s value
can be accessed, is the local storage of the function.

Global variables.

Global variables allow you to cross the boundary between separate


functions to access a variable’s value. The global statement specifies that
you want the variable to be the same variable everywhere that it’s defined
as global.

Static variables.

Static variables provide a variable that isn’t destroyed when a function


ends. You can use the static variable value again the next time you call
the function, and it will still have the same value as when it was last used
in the function.

A static variable remembering its last value

<?php

// Define the function

function birthday( ){

// Define age as a static variable

static $age = 0;

// Add one to the age value

$age = $age + 1;

// Print the static age variable

echo "Birthday number $age<br />";

}
// Set age to 30

$age = 30;

// Call the function twice

birthday( );

birthday( );

// Display the age

echo "Age: $age<br />";

?>

This displays:

Birthday number 1

Birthday number 2

Age: 30

Super global variables.

PHP uses special variables called super globals to provide information


about the PHP script’s environment. These variables don’t need to be
declared as global. They are automatically available, and they provide
important information beyond the script’s code itself, such as values from
a user’s input.

PHP super globalsVariable array name Contents

$GLOBALS Contains any global variables that are accessible for the
local script. The variable names are used toselect which part of the
array to access.

$_SERVER Contains information about the web server environment.

$_GET Contains information from GET requests (a form


submission). These values should be checkedbefore use.

$_POST Contains information from POST requests (another type of


form submission). These values shouldbe checked before use.
$_COOKIE Contains information from HTTP cookies.

$_FILES Contains information from POST file uploads.

$_ENV Contains information about the scripts environment.

$_REQUEST Contains information from user inputs. These values


should be checked before use. $_GET or$_POST should be used
instead of $_REQUEST as they are more specific.

$_SESSION Contains information from any variables registered in a


session.

An example of a super global is $_SERVER["PHP_SELF"]. This


variable contains the name of the running script and is part of the
$_SERVER array.

PHP_SELF being used with a file called test.php

<?php

echohtmlentities($_SERVER["PHP_SELF"]);

?>

This outputs:

/test.php

Data Types

• Variables can store data of different types, and different data types
can do

different things.

PHP supports the following data types:

• String

• Integer

• Float (floating point numbers - also called double)

• Boolean
• Array

• Object

• NULL

• Resource

PHP String

• A string is a sequence of characters, like "Hello world!".

• A string can be any text inside quotes. You can use single or double
quotes:

Example

<html>

<body>

<?php

$x = "Hello world!";

$y = 'Hello world!';

echo $x;

echo "<br>";

echo $y;

?>

</body>

</html>

OUTPUT:

Hello world!

Hello world!

Strings
• Get The Length of a String

• The PHP strlen() function returns the length of a string.

• The example below returns the length of the string "Hello world!":

Example

<html>

<body>

<?php

Echostrlen("Helloworld!"); ?>

</body>

</html>

OUPUT:

12

Count The Number of Words in a String

The PHP str_word_count() function counts the number of words in a


string:

Example

<html>

<body>

<?php

echostr_word_count("Hello world!");

?>

</body>

</html>

OUPUT:

2
Reverse a String

• The PHP strrev() function reverses a string:

Example

<html>

<body>

<?php

echostrrev("Hello world!");

?>

</body>

</html>

OUTPUT:

!dlrowolleH

Search For a Specific Text Within a String

• The PHP strpos() function searches for a specific text within a


string.

• If a match is found, the function returns the character position of


the first match. Ifno match is found, it will return FALSE.

• The example below searches for the text "world" in the string
"Hello world!":

Example

<html>

<body>

<?php

Echostrpos("Hello world!", "world");

?>

</body>
</html>

OUPUT:

Replace Text Within a String

• The PHP str_replace() function replaces some characters with some


other

characters in a string.

• The example below replaces the text "world" with "Dolly":

Example

<html>

<body>

<?php

Echostr_replace("world", "Dolly", "Hello world!");

?>

</body>

</html>

OUPUT:

Hello Dolly!

PHP Integer

An integer data type is a non-decimal number between -2,147,483,648


and

2,147,483,647.

To have double quotes within string.

can insert variables such as $my_stringinto string


definitions,provided that you use double quotes to start and end your
string
<?php

$my_string = "SDNBVC College\"s";

echo "Time for $my_string";

?>

Output:

Time for SDNBVC College"s

Using single quotes to start and end your string does not
allow a variable,to be placed in the string,see the below
example.

<?php

$my_string = "SDNBVC College\"s";

echo 'Time for $my_string';

?>

Output:

Time for $my_string

Comparing strings

Use strcmp (string1, string2) to compare two strings including the case.
The return
value is 0 if the two strings have the same text. Any nonzero value
indicates they are
not the same.
Use strcasecmp (string1, string2) to compare two strings without
comparing the
case. The return value is 0 if the two strings have the same text. Any
nonzero value
indicates they’re not the same.

Using strcasecmp to compare two strings

<?php
$name1 = "Bill";
$name2 = "BILL";
$result = strcasecmp($name1, $name2);
if (!$result){
echo "They match.";
}
?>

Output :

They match.

String Comparison operators


Examples

$name1 == $name2 Equal True, if $name1 is equal to $name2.

$name1 === $name2 Identical True, if $name1 is equal to $name2, and if


they are of the same type.

$name1 != $name2 Not Equal True, if $name1 is not equal to $name2.

$name1 <> $name2 Not Equal True, if $name1 is not equal to $name2, or
if they are not ofthe same type.$name1 < $name2 Less Than True, if
$name1 is strictly less than $name2.

$name1 > $name2 Greater Than True, if $name1 is strictly greater than
$name2.

$name1 <= $name2 Less Than or Equal To True, if $name1 is less than
or equal to $name2.

$name1 >= $name2 Greater Than or Equal To True, if $name1 is greater


than or equal to $name2.

Concatenation
<?php
$my_string = "Hello Max. My name is: ";
$newline = "<br />";
echo $my_string . "Pooja" . $newline;

echo "Hi, I'm Max. Who are you? " . $my_string . "Pooja";

?>
Output:
Hello Max. My name is: Pooja
Hi, I'm Max. Who are you? Hello Max. My name is: Pooja

Rules for integers:

• An integer must have at least one digit

• An integer must not have a decimal point

• An integer can be either positive or negative

• Integers can be specified in three formats: decimal (10-based),


hexadecimal (16-

based - prefixed with 0x) or octal (8-based - prefixed with 0)

• In the following example $x is an integer. The PHP var_dump()


functionreturns the data type and value:

Example

<html>

<body>

<?php

$x = 5985;

var_dump($x);

?>

</body>

</html>

OUTPUT:

int(5985)

PHP Float

• A float (floating point number) is a number with a decimal point or


a number inexponential form.
• In the following example $x is a float. The PHP var_dump()
function returns thedata type and value:

Example

<html>

<body>

<?php

$x = 10.365;

var_dump($x);

?>

</body>

</html>

OUTPUT:

float(10.365)

PHP Boolean

A Boolean represents two possible states: TRUE or FALSE.

$x = true;

$y = false;

Booleans are often used in conditional testing.

Variables

• Variables are "containers" for storing information.

• Creating (Declaring) PHP Variables

• In PHP, a variable starts with the $ sign, followed by the name of


the variable:

Example

<html>
<body>

<?php

$txt = "Hello world!";

$x = 5; Output:

$y = 10.5;

Hello world!

echo $txt; 5

echo "<br>"; 10.5

echo $x;

echo "<br>";

echo $y;

?>

</body>

</html>

After the execution of the statements above, the variable $txt will
hold the value Helloworld!, the variable $x will hold the value 5, and
the variable $y will hold the value 10.5.

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 avariable. It is created the moment you first assign a
value to it.

Rules for PHP variables:

A variable can have a short name (like x and y) or a more descriptive


name (age,

carname, total_volume).

• 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 (Az, 0-9, and _ )

• Variable names are case-sensitive ($age and $AGE are two different
variables)

Output Variables

• The PHP echo statement is often used to output data to the screen.

The following example will show how to output text and a variable:

Example

<html>

<body>

<?php

$txt = "W3Schools.com";

echo "I love $txt!";

?>

</body>

</html>

Example

<html>

<body>

<?php

$txt = "W3Schools.com";

echo "I love " . $txt . "!";

?>
</body>

</html>

Output:

I love W3Schools.com!

Output:

I love W3Schools.com!

Example

<html>

<body>

<?php

$x = 5;

$y = 4;

echo $x + $y;

?>

</body>

</html>

PHP Variables Scope

• In PHP, variables can be declared anywhere in the script.

• The scope of a variable is the part of the script where the variable
can be

referenced/used.

PHP has three different variable scopes:

• local

• global

• static
Global and Local Scope

A variable declared outside a function has a GLOBAL SCOPE

and can only beaccessed outside a function:

Example

<html>

<body>

<?php

$x = 5; // global scope

FunctionmyTest() {

// using x inside this function will generate an error

echo "<p>Variable x inside function is: $x</p>";

myTest();

echo "<p>Variable x outside function is:

$x</p>"; ?>

</body>

</html>

Output:

OUTPUT:

Variable x inside function is:

Variable x outside function is: 5

A variable declared within a function has a LOCAL SCOPE, can


only be accessedwithin that function:

Example
<html>

<body>

<?php

Function myTest() {

$x = 5; // local scope

echo "<p>Variable x inside function is: $x</p>";

myTest();

// using x outside the function will generate an error

echo "<p>Variable x outside function is: $x</p>";

?>

</body>

</html>OUTPUT:

The global Keyword

• The global keyword is used to access a global variable from within a


function.
• To do this, use the global keyword before the variables (inside the
function):

Example

<html>
<body>
<?php
$x = 5;
$y = 10;
Function myTest() {
global $x, $y;
$y= $x + $y;
}
myTest(); // run function
echo $y; // output the new value for variable
?>
</body>
</html>

Output:15

The static Keywordnormally, when a function is completed/executed,


all of its variables are deleted.However, sometimes we want a local
variable NOT to be deleted. We need it for afurtherjob.To do this,
use the static keyword when you first declare the variable:

Example

<html>
<body>
<?php
FunctionmyTest() {
static $x = 0; (if not static given , we will get ‘0’ as output for all echo
stmt)
echo $x;
$x++;
}
myTest();
echo "<br>";
myTest();
echo "<br>";
myTest();
?>
</body>
</html>
Output:
0
1
2

echo and print Statements

• In PHP there are two basic ways to get output: echo and print.

• echo and print are more or less the same. They are both used to
output data to
the screen.
• The differences are small: echo has no return value while print has
a return valueof 1 so it can be used in expressions. echo can take
multiple parameters(although such usage is rare) while print can
take one argument. echo ismarginally faster than print.

echo Statement

The echo statement can be used with or without parentheses: echo or


echo().

Display Text

The following example shows how to output text with the echo
command (notice that thetext can contain HTML markup):

Example

<html>

<body>

<?php

echo "<h2>PHP is Fun!</h2>";

echo "Hello world!<br>";

echo "I'm about to learn PHP!<br>";

echo "This ", "string ", "was ", "made ", "with
multipleparameters.";

?> I am from india \”


</body>

</html>

OUTPUT:

PHP is Fun!

Hello world!

I'm about to learn PHP!

This string was made with multiple parameters.

Display Variables

The following example shows how to output text and variables with
the echo statement:

Example

<html>
<body>
<?php
$txt1 = "Learn PHP"; $txt2= "W3Schools.com"; $x =5;
$y = 4;
echo "<h2>" . $txt1 . "</h2>";
echo "Study PHP at " . $txt2 . "<br>";
echo $x + $y;
?>
</body>
</html>

OUTPUT:

Learn PHP

Study PHP at

W3Schools.com 9

The PHP print Statement

• The print statement can be used with or without parentheses: print


or print().
The following example shows how to output text with the print
command (notice that thetext can contain HTML markup):

Example

<html>
<body>
<?php
print "<h2>PHP is Fun!</h2>";
print "Hello world!<br>";
print "I'm about to learn
PHP!"; ?>
</body>
</html>

OUTPUT:

PHP is Fun!

Hello world!

I'm about to learn PHP!

Display Variables

The following example shows how to output text and variables with
the print statement:

Example

<html>
<body>
<?php
$txt1 = "Learn PHP";
$txt2= "W3Schools.com";
$x = 5;
$y = 4;
print "<h2>" . $txt1 . "</h2>";
print "Study PHP at " . $txt2 ." ";
print $x + $y . "a.m";
?>
</body>
</html>

OUTPUT:

Learn PHP
Study PHP atW3Schools.com 9a.m

PHP Object

• An object is a data type which stores data and information on how


to process thatdata.

• In PHP, an object must be explicitly declared.

• First we must declare a class of object. For this, we use the class
keyword. A

class is a structure that can contain properties and methods:

Example

<html>

<body>

<?php

class Car {

function Car() {

$this->model = "VW";

// create an object

$herbie = new Car();

$honda = new car();

// show object properties

Echo $herbie->model ;

echo "<br>";

echo $honda->model;

?>
</body>

</html>

OUPUT:

VW

VW

PHP NULL Value

• 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.

• Variables can also be emptied by setting the value to NULL:

Example

<html>
<body>
<?php
$x = "Hello world!";
$x = null;//if not having this stmt ,we will get O/P - string(12) "Hello
world!"
var_dump($x);//The information holds type and value of the
variable(s).
?>
</body>
</html>

OUTPUT:

NULL

Strings

<?php

$my_string = "Margaritaville - Suntan Oil Application!";


echo "Margaritaville - Suntan Oil Application!";

?>

if you want to use a single quote within a string marked with single
quotes, you have to escape the single quote with a backslash (\).

Comparing strings

PHP has functions to compare strings that aren’t exactly alike. For
example, you maywant to consider “Bill” to be the same as “BILL,”
ignoring the case of the string.

Use strcmp (string1, string2) to compare two strings including the


case. The returnvalue is 0 if the two strings have the same text. Any
nonzero value indicates they arenot the same.

Use strcasecmp (string1, string2) to compare two strings without


comparing thecase. The return value is 0 if the two strings have the
same text. Any nonzero valueindicates they’re not the same.

compares “Bill” to “BILL” without considering the case. The if


statement checks to see whether the value of result is not TRUE, and
performs an actionbased on that check.

Using strcasecmp to compare two strings

<?php

$name1 = "Bill";

$name2 = "BILL";

$result = strcasecmp($name1, $name2);

if (!$result){

echo "They match.";

?>

Output:

They match.
Comparison operators

$name1 == $name2 Equal True, if $name1 is equal to $name2.

$name1 === $name2 Identical True, if $name1 is equal to $name2,


and if they are of thesame type.

$name1 != $name2 Not Equal True, if $name1 is not equal to


$name2.

$name1 <> $name2 Not Equal True, if $name1 is not equal to


$name2, or ifthey are not ofthe same type.

$name1 < $name2 Less Than True, if $name1 is strictly less than
$name2.

$name1 > $name2 Greater Than True, if $name1 is strictly greater


than $name2.

$name1 <= $name2 Less Than or Equal To True, if $name1 is less


than or equal to $name2.

$name1 >= $name2 Greater Than or Equal To True, if $name1 is


greater than or equal to $name2

Concatenation

Concatenation combines one or more text strings and variables

Concatenating strings together

<?php

$my_string = "Hello Max. My name is: ";

$newline = "<br />";

echo $my_string . "Paula" . $newline;

echo "Hi, I'm Max. Who are you? " . $my_string . "Paula";

?>
If you combine a string with another data type, such as a
number, the result is also a string .

<?php

$str = "This is an example of ". 3 ." in the middle of a string.";

echo $str;

?>

Output:

This is an example of 3 in the middle of a string.

Constants

A constant is an identifier (name) for a simple value. The


value cannot be changed during the script.

A valid constant name starts with a letter or underscore


(no $ sign before the constant name).

Note: Unlike variables, constants are automatically global


across the entire script.

To create a constant, use the define() function.

Syntax

define(name, value, case-insensitive)

Parameters:

 name: Specifies the name of the constant


 value: Specifies the value of the constant
 case-insensitive: Specifies whether the constant name should be
case-insensitive. Default is false

Example

<!DOCTYPE html>

<html>
<body>

<?php

// case-sensitive constant name

define("GREETING", "Welcome to W3Schools.com!");

echo GREETING;

?>

</body>

</html>

Output:

Welcome to W3Schools.com!

Differences between constants and variables:

• It’s common practice to capitalize a variable name for constants.

• Constants do not have a dollar sign ($) at the start of their names.

• Constants can be defined only by using the define function, not by


simple assignment.

• Constants are defined and accessed globally.

• Constants cannot be redefined or undefined once they have been set.

• Constants can evaluate only to scalar values

How to use a constant in your program

<?php
define("HELLO", "Hello world! ");
echo HELLO; // outputs "Hello world!"
$constant_name = "HELLO";
echo constant($constant_name);
?>
outputs:
Hello world! Hello world!
Predefined constants
PHP provides a few constants that are predefined similarly to the way we
have somesuper globals. Examples of these include __ FILE__ , which
returns the name of thePHP file that’s being executed; and __ LINE__ ,
which returns the line number in thatfile.There are two underscores
before and after the predefined constants.

<?php
define("HELLO", "Hello world! ");
echo HELLO; // outputs "Hello world!"
$constant_name = "HELLO";
echo constant($constant_name);
echo "<br />"."Executing line " . __LINE__ ." of PHP script " .
__FILE__;
?>

Output

Hello world! Hello world!


Executing line 6 of PHP script C:\xampp\htdocs\ex1.php

Combined assignment
Combined assignment operators provide a shortcut for performing two
commontasks at the same time.
Combined assignment operators take the form of the arithmetic operator
directlyfollowed by an equals sign (=).
For example, the statement:
$c=$c+1; is equivalent to:
$c +=1;

Autoincrement andautodecrement

The autoincrement operator is ++ and is used like this:


$counter++;
This is completely equivalent to, and even more
professional-looking, than:
$counter+=1;

Preincrement and –decrement

<?php
$test=1;
echo "Preincrement: ".(++$test);
echo "<BR>";
echo "Value afterwords: ".$test;
echo "<BR>";
$test=1;
echo "Postincrement: ".($test++);
echo "<BR>";
echo "Value afterwords: ".$test;
?>

Output:
Preincrement: 2
Value afterwords: 2
Postincrement: 1
Value afterwords: 2

PHP Decision-Making

 A statement is code that performs a task.


 Statements are made up of expressions and operators. An
expression is a piece of code that evaluates to a value
PHP has many types of operators, including:
• Arithmetic operators
• Array operators
• Assignment operators
• Bitwise operators
• Comparison operators
• Execution operators
• Incrementing/decrementing operators
• Logical operators
• String operators

Each operator has four critical properties


 Number of operands
 Type of operands
 Order of precedence
 Operator associativity

Following table lists PHP operators with decreasing order of


precedence

PHP operators sorted by order ofprecedence from highest to lowest.


Operators with the same level number are all ofthe same precedence.
Associativity
All operators process their operators in a certain direction. This direction is
calledassociativity, and it depends on the type of operator. Most operators
are processedfromleft to right, which is called left associativity. For example,
in the expression 3 +5 – 2, 3 and 5 are added together, and then 2 is
subtracted fromthe result, evaluatingto 8. While left associativity means that
the expression is evaluated from left to right,right associativity means the
opposite.

Conditionals
There are three primary conditionals in PHP:

• if
• ? : :(shorthand for an if statement)
• switch
The switch statement is useful when you have multiple things you want to
do andneed to take different actions based on the contents of a variable.

The if Statement

The syntax for the ifstatement is:


if (conditional expression){
block of code;
}

if ($username == "Admin") {
echo ('Welcome to the admin page.');
}
The curly braces aren’t needed if you want to execute only one statement

The else statement

if ($username == "Admin"){
echo ('Welcome to the admin page.');
}
else {
echo ('Welcome to the user page.');

The elseif statement


if ($username == "Admin"){
echo ('Welcome to the admin page.');
}
elseif ($username == "Guest"){
echo ('Please take a look around.');
}
else {
echo ("Welcome back, $username.");

The ? Operator
The ?operator is a ternary operator, which means it takes three
operands The conditionalexpression determines the value of the
expression. A colon (:) is used to separatethe expressions, as shown
here:

{expression} ?
return_when_expression_true :return_when_expression_false;

<?php
$logged_in = TRUE;
$user = "Admin";
$banner = ($logged_in==TRUE)?"Welcome back, $user!":"Please
login.";
echo "$banner;?>

Output:
Welcome back, Admin!

The switch Statement


The switch statement compares an expression to numerous values.

For example, you might have avariable called $action, which may have
the values add, modify, and delete

Using if to test for multiple values

if ($action == "ADD") {
echo "Perform actions for adding.";
echo "As many statements as you like can be in each block.";
}
elseif ($action == "MODIFY") {
echo "Perform actions for modifying.";
}
elseif ($action == "DELETE") {
echo "Perform actions for deleting.";
}

Using switch to test for multiple values


switch ($action) {
case "ADD":
echo "Perform actions for adding.";
echo "As many statements as you like can be in each block.";
break;
case "MODIFY":
echo "Perform actions for modifying.";
break;
case "DELETE":
echo "Perform actions for deleting.";

Breaking out
If you want only the code in the matching block to execute, place a break
keyword at the end of that block. When PHP comes across the break
keyword, processing jumps to the next line after the entire switch
statement

Default Statement:
Use the DEFAULT: statement for the SWITCH’s last case statement

switch ($action) {
case "ADD":
echo "Perform actions for adding.";
echo "As many statements as you like can be in each block.";
break;
case "MODIFY":
echo "Perform actions for modifying.";
break;
case "DELETE":
echo "Perform actions for deleting.";
break;
default:
echo "Error: Action must be either ADD, MODIFY, or DELETE.";}

Looping
while Loops

The syntax for a while loop is:


while (expression)
{
code to execute;
}

A sample while loop that counts to 10


<?php
$num = 1;
while ($num<= 10){
print "Number is $num<br />";
$num++;
}
print 'Done.';?>

do … while Loops
The do ... while loop takes an expression such as a while statement
but places it atthe end. The syntax is:
do {
code to execute;
} while (expression);

This loop is useful when you want to execute a block of code at least
once regardlessof the expression value

Counting to 10 with do … while


<?php
$num = 1;
do {
echo "Number is ".$num."<br />";
$num++;
} while ($num<= 10);
echo "Done.";?>

for Loops
forloops provide the same general functionality as while loops, but
also provide fora predefined location for initializing and changing a
counter value. Their syntax is:
for (initialization expression; condition expression; modification
expression){
code that is executed;

An example for loop is:


<?php
for ($num = 1; $num<= 10; $num++) {
print "Number is $num<br />\n";
}
?>
This produces the following:
Number is 1
Number is 2
Number is 3
Number is 4
Number is 5
Number is 6
Number is 7
Number is 8
Number is 9
Number is 10

continue Statements
You can use the continue statement to stop processing the current
block of code in aloop and jump to the next iteration of the loop.

Using continue instead of break


<?php
$counter=-3;
for (;$counter<10;$counter++){
//check for division by zero
if ($counter==0){
echo "Skipping to avoid division by zero.<br>";
continue;
}
echo "100/$counter ",100/$counter,"<br />";}?>

Functions
PHP User Defined Functions
 A function is a block of statements that can be used repeatedly
in a program.
 A function will not execute automatically when a page loads.
 A function will be executed by a call to the function.

A user-defined function declaration starts with the word function:

Syntax
FunctionfunctionName() {
code to be executed;
}
A function name must start with a letter or an underscore. Function
names are NOT case-sensitive.
<?php
function writeMsg() {
echo "Hello world!";
}

writeMsg(); // call the function


?>

PHP Function Arguments


Information can be passed to functions through arguments. An
argument is just like a variable.

Arguments are specified after the function name, inside the


parentheses. You can add as many arguments as you want, just
separate them with a comma.

In strict mode, only a value corresponding exactly to the type


declaration will be accepted, otherwise a TypeError will be thrown.
The only exception to this rule is that an int value will pass a float
type declaration.
To enable strict mode, the declare statement is used with the
strict_types declaration:
<?php
declare(strict_types=1);

function sum(int $a, int $b) {


return $a + $b;
}

var_dump(sum(1, 2));
var_dump(sum(1.5, 2.5));
?>
We will get error msg like below
Fatal error: Uncaught TypeError: Argument 1 passed to sum() must be an
instance of intt, int given, called in C:\xampp\htdocs\ex1.php on line 8 and
defined in C:\xampp\htdocs\ex1.php:4 Stack trace: #0 C:\xampp\htdocs\
ex1.php(8): sum(1, 2) #1 {main} thrown in C:\xampp\htdocs\ex1.php on
line 4

<?php
function sum(int $a, int $b) {
return $a + $b;
}

var_dump(sum(1, 2));

// These will be coerced to integers: note the


output below!
var_dump(sum(3, 2.8));
?>
Output:
int(3) int(5)
PHP Default Argument Value

<?php declare(strict_types=1); // strict requirement ?>


<!DOCTYPE html>
<html>
<body>

<?php
functionsetHeight(int $minheight = 50) {
echo "The height is : $minheight<br>";
}

setHeight(350);
setHeight();
setHeight(135);
setHeight(80);
?>

</body>
</html>

Output:
The height is : 350
The height is : 50
The height is : 135
The height is : 80

PHP Functions - Returning values

<?php declare(strict_types=1); // strict requirement ?>


<!DOCTYPE html>
<html>
<body>

<?php
function sum(int $x, int $y) {
$z = $x + $y;
return $z;
}

echo "5 + 10 = " . sum(5,10) . "<br>";


echo "7 + 13 = " . sum(7,13) . "<br>";
echo "2 + 4 = " . sum(2,4);
?>
</body>
</html>

Output:
5 + 10 = 15
7 + 13 = 20
2+4=6

PHP Functions - Returning values


<?php declare(strict_types=1);
functionaddNumbers(float $a, float $b) : float //return type

{
return $a + $b;
}
echoaddNumbers(1.2, 5.2);
?>

Output:
6.4

Passing Arguments by Reference


When a function argument is passed by reference, changes to the
argument also change the variable that was passed in. To turn a
function argument into a reference, the & operator is used:
<!DOCTYPE html>
<html>
<body>

<?php
functionadd_five(&$value) {
$value += 5;
}

$num = 2;
add_five($num);
echo $num;
?>

</body>
</html>
Output:
7

Testing a Function
To check for the existence of functions , the function function_exists it
takes a string with a function’s name and returns TRUE or FALSE
depending on whether the function has been defined. For example,
the following code tests a function:

<?php
$test=function_exists("test_this");
if ($test == TRUE)
{
echo "Function test_this exists.";
}
else
{
echo "Function test_this does not exist.";
//call_different_function( );
}
?>

Output:
Function test_this does not exist.

PHP provides four functions that enable you to insert code from
other files:
• include
• require
• include_once
• require_once

The include Statement


This function is used to copy all the contents of a file called within the
function, text wise into a file from which it is called. This happens
before the server executes the code.
A sample include file called add.php
<?php
function add( $x, $y ){
return $x + $y;
}
?>

->assumes that add.phpis in the same directory as the script


Using the include function
<?php
include('add.php');
echo add(2, 2);
?>

Output:
4

The include_once statement


A problem may arise when you include many nested PHP scripts
because theincludestatement doesn’t check for scripts that have
already been included.
For example, if you did this:
<?phpinclude('add.php');include('add.php');
echo add(2, 2);
?>
you’d get this error:
Fatal error: Cannot redeclareadd( ) (previously declared in
/home/www/htmlkb/oreilly/ch5/add.php:2) in
/home/www/htmlkb/oreilly/ch5/add.phponline 2
This directory may not be where your file is located; your file will go
wherever you’vedesignated a place for it. To avoid this type of error,
you should use the include_once
statement.

Example : Using the include function


<?php
include('add.php');
echo add(2, 2);
?>
Example 5-9. Using include_once to include a file
<?php
include_once('add.php');
include_once('add.php');
echo add(2, 2);
?>

Output:
4

PHP require() function:


The require() function performs same as the include() function. It
also takes the file that is required and copies the whole code into the
file from where therequire() function is called.

ex1.php
<?php
// File to be included
echo "Hello Friends";
?>

ex2.php
<?php
require("ex1.php");
echo "<br>Above line is Received from ex1.php"
?>

Output while running ex2.php


Hello Friends
Above line is Received from ex1.php

When ex2.php changed by adding another require function for the same
ex1.php file ,output will be
<?php
require("ex1.php");
require("ex1.php");
echo "<br>Above line is Received from ex1.php"
?>

Output:
Hello FriendsHello Friends
Above line is Received from ex1.php

require_once() Function:

The require_once() function in PHP is used to include one PHP file


into another PHP file. It provides us with a feature that if a code
from a PHP file is already included in a specified file then it will not
include that code again if we use the require_once() function. It
means that this function will add a file into another only once.

In case this function does not locate a specified file then it will
produce a fatal error and will immediately stop the execution.
Object-Oriented Programming

Procedural programming is about writing procedures or functions


that perform operations on the data, while object-oriented
programming is about creating objects that contain both data and
functions.

Object-oriented programming has several advantages over


procedural programming:

 OOP is faster and easier to execute


 OOP provides a clear structure for the programs
 OOP helps to keep the PHP code DRY "Don't Repeat
Yourself""Don't Repeat Yourself" (DRY) principle is about
reducing the repetition of code. You should extract out the
codes that are common for the application, and place them at a
single place and reuse them instead of repeating it., and makes
the code easier to maintain, modify and debug
 OOP makes it possible to create full reusable applications with
less code and shorter development time

A class is a template for objects, and an object is an instance of a


class.
When the individual objects are created, they inherit all the
properties and behaviors from the class, but each object will have
different values for the properties.

Define a Class
A class is defined by using the class keyword, followed by the name of
the class and a pair of curly braces ({}). All its properties and
methods go inside the braces:

<?php
class Fruit {
// Properties
public $name;
public $color;

// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
?>
Define Objects

Objects of a class are created using the new keyword.

The $this keyword refers to the current object, and is only available
inside methods.
In the example below, $apple and $banana are instances of the class
Fruit:

<?php
class Fruit {
// Properties
public $name;
public $color;

// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}

$apple = new Fruit();


$banana = new Fruit();
$apple->set_name('Green Apple');
$banana->set_name('Yellow Banana');

echo $apple->get_name();
echo "<br>";
echo $banana->get_name();
?>

Output:
Green Apple
Yellow Banana

We canchange the value of the $name property in two ways:

1. Inside the class - by adding a set_name() method and use $this


(as above example program)
2. Outside the class - by directly changing the property value –
below is the example
<?php
class Fruit {
public $name;
}
$apple = new Fruit();
$apple->name = "Apple";

echo $apple->name;
?>

Output:
Apple

PHP - instanceof

You can use the instanceof keyword to check if an object belongs to a


specific class or not.

<?php
class Fruit {
public $name;
}
$apple = new Fruit();
var_dump($apple instanceof Fruit);

?>

Output:
bool(true)
Constructor:

A constructor allows you to initialize an object's properties upon


creation of the object.

If you create a __construct() function, PHP will automatically call


this function when you create an object from a class.

<?php
class Fruit {
public $name;
public $color;

function __construct($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}

$apple = new Fruit("Apple");


echo $apple->get_name();
?>

Output

Apple
Destructor:

The __destruct Function

A destructor is called when the object is destructed or the script is


stopped or exited.

If you create a __destruct() function, PHP will automatically call this


function at the end of the script.( two underscores)
<?php
class Fruit {
public $name;
public $color;

function __construct($name) {
$this->name = $name;
}
function __destruct() {
echo "The fruit is {$this->name}.";
}
}

$apple = new Fruit("Apple");


?>

Output:
The fruit is Apple.

PHP - Access Modifiers


Properties and methods can have access modifiers which control
where they can be accessed.

There are three access modifiers:

public - the property or method can be accessed from everywhere.


This is default
protected - the property or method can be accessed within the class
and by classes derived from that class
private - the property or method can ONLY be accessed within the
class

In the following example we have added three different access


modifiers to three properties (name, color, and weight).
Here, if you try to set the name property it will work fine (because
the name property is public, and can be accessed from everywhere).
However, if you try to set the color or weight property it will result in
a fatal error (because the color and weight property are protected
and private).

<?php
class Fruit {
public $name;
protected $color;
private $weight;
}

$mango = new Fruit();


$mango->name = 'Mango'; // OK
echo $mango->name;
$mango->color = 'Yellow'; // ERROR
$mango->weight = '300'; // ERROR
?>

Output:
Mango

In the next example we have added access modifiers to two functions.


Here, if you try to call the set_color() or the set_weight() function it
will result in a fatal error (because the two functions are considered
protected and private), even if all the properties are public:
<?php
class Fruit {
public $name;
public $color;
public $weight;

function set_name($n) { // a public


function (default)
$this->name = $n;
}
protected function set_color($n) { // a
protected function
$this->color = $n;
}
private function set_weight($n) { // a
private function
$this->weight = $n;
}
}
$mango = new Fruit();
$mango->set_name('Mango'); // OK
$mango->set_color('Yellow'); // ERROR
$mango->set_weight('300'); // ERROR
?>

Inheritance
Inheritance in OOP = When a class derives from another class.

The child class will inherit all the public and protected properties
and methods from the parent class. In addition, it can have its own
properties and methods.

An inherited class is defined by using the extends keyword.

Example
<?php
class Fruit {
public $name;
public $color;
public function __construct($name,
$color) {
$this->name = $name;
$this->color = $color;
}
public function intro() {
echo "The fruit is {$this->name} and
the color is {$this->color}.";
}
}

// Strawberry is inherited from Fruit


class Strawberry extends Fruit {
public function message() {
echo "Am I a fruit or a berry? ";
}
}
$strawberry
= new Strawberry("Strawberry", "red");
$strawberry->message();
$strawberry->intro();
?>

Output:
Am I a fruit or a berry? The fruit is Strawberry and the color is red.

Explanation;
The Strawberry class is inherited from the Fruit class.

This means that the Strawberry class can use the public $name and
$color properties as well as the public __construct() and intro()
methods from the Fruit class because of inheritance.

The Strawberry class also has its own method: message().

PHP - Inheritance and the Protected Access Modifier

Below example, if we try to call a protected method (intro()) from


outside the class, we will receive an error. public methods will work
fine!
<?php

class Fruit {
public $name;
public $color;
public function __construct($name,
$color) {
$this->name = $name;
$this->color = $color;
}
protected function intro() {
echo "The fruit is {$this->name} and
the color is {$this->color}.";
}
}

class Strawberry extends Fruit {


public function message() {
echo "Am I a fruit or a berry? ";
}
}
// Try to call all three methods from
outside class
$strawberry
= new Strawberry("Strawberry", "red"); //
OK. __construct() is public
$strawberry->message(); // OK. message() is
public
$strawberry->intro(); // ERROR. intro() is
protected
?>

Output
Am I a fruit or a berry? The fruit is Strawberry and the color
is red.

In the below example all works fine! It is because we call the


protected method (intro()) from inside the derived class.

<?php
class Fruit {
public $name;
public $color;
public function __construct($name,
$color) {
$this->name = $name;
$this->color = $color;
}
protected function intro() {
echo "The fruit is {$this->name} and
the color is {$this->color}.";
}
}

class Strawberry extends Fruit {


public function message() {
echo "Am I a fruit or a berry? ";
// Call protected method from within
derived class - OK
$this -> intro();
}
}

$strawberry
= new Strawberry("Strawberry", "red"); //
OK. __construct() is public
$strawberry->message(); // OK. message() is
public and it calls intro() (which is
protected) from within the derived class
?>

Output
Am I a fruit or a berry? The fruit is Strawberry and the color
is red.

Overriding Inherited Methods

Inherited methods can be overridden by redefining the methods (use


the same name) in the child class.

Look at the example below. The __construct() and intro() methods in


the child class (Strawberry) will override the __construct() and
intro() methods in the parent class (Fruit):
<?php
class Fruit {
public $name;
public $color;
public function __construct($name,
$color) {
$this->name = $name;
$this->color = $color;
}
public function intro() {
echo "The fruit is {$this->name} and
the color is {$this->color}.";
}
}
class Strawberry extends Fruit {
public $weight;
public function __construct($name,
$color, $weight) {
$this->name = $name;
$this->color = $color;
$this->weight = $weight;
}
public function intro() {
echo "The fruit is {$this->name}, the
color is {$this->color}, and the weight is
{$this->weight} gram.";
}
}

$strawberry
= new Strawberry("Strawberry", "red", 50);
$strawberry->intro();
?>

Output:
The fruit is Strawberry, the color is red, and the weight is 50
gram.
Final Keyword
final keyword can be used to prevent class inheritance or to prevent
method overriding.

The following example shows how to prevent class inheritance:


<!DOCTYPE html>
<html>
<body>

<?php
final class Fruit {
}

class Strawberry extends Fruit {


}
?>

</body>
</html>

Output:
PHP Fatal error: Class Strawberry may not inherit from final
class (Fruit)

The following example shows how to prevent method


overriding:

<!DOCTYPE html>
<html>
<body>

<?php
class Fruit {
final public function intro() {
}
}

class Strawberry extends Fruit {


// will result in error
public function intro() {
}
}
?>

</body>
</html>

Output
PHP Fatal error: Cannot override final method Fruit::intro()

Parent operator
It’salso possible to override existing functionality fromthe superclass
to provide yourown new code. You simply redefine the function in
the new class.

When extending classes to override functions in your class that are


already defined inthe superclass, you can still execute the code
fromthe parent class and then add onyour own functionality. To call
the parent class method before your code, use:

parent::method_from_parent

This calls the parent method in the superclass.

<?php
class Cat {

function eat( ){
echo "Chomp chomp.</br>";
}

function Meow( ){
echo "Meow.</br>";
}
}

classDomestic_Cat extends Cat {

functionDomestic_Cat( ) {
echo " Domestic cat constructor. </br>";
}

function eat( ) {

parent::eat( );
$this->meow( );
}
}

$Domestic_Cat=new Domestic_Cat();
$Domestic_Cat->eat();
?>

Output:
Domestic cat constructor.
Chomp chomp.
Meow.

This calls the eat function from the superclass, and then adds the
code for meowing.
When we extend a class and declare your own constructor, PHP
won’t automaticallycall the constructor of the parent class.Weshould
always call the constructorof the parent class to be sure all
initialization code gets executed.

Static Methods and Variables


Methods and variables can also be used and accessed if they are
defined as static in aclass static means the method or variable is
accessible through the class definition and not just through objects.

The :: operator allows you to refer to variables and methods on a


class that doesn’tyet have any instances or objects created for it.

Below Example shows how to call a static method using ::, and how
the usual method-calling syntax of -> doesn’t work ( Wrong while
executing the program it works), even after an instance of the class
has been created. (PHP doesn’t report an
error—it just doesn’t work.)

<?php
class Cat {
}

classHypnotic_Cat extends Cat {

functionHypnotic_Cat( ) {
}

public static function hypnotize( ) {


echo ("The cat was hypnotized.");
return;
}
}

Hypnotic_Cat::hypnotize( );
$hypnotic_cat = new Hypnotic_Cat( );
// Does nothing - in book it was given like below will not work...but it
is working
$hypnotic_cat->hypnotize( );
?>

Output:
The cat was hypnotized.The cat was hypnotized.
Variable References
Theampersand operator (&) is used to indicate that you’re interested
in the location inmemory that a variable points to instead of its value.
PHP references allow you to create two variables to refer to the same
content. Therefore,changing the value of one variable can change the
value of another.

<?php
$some_variable = "Hello World!";
$some_reference = &$some_variable;
echo $some_variable;

echo $some_reference;

$some_reference = "Guten Tag World!";


echo $some_variable;
echo $some_reference;
?>

Output
Hello World!HelloWorld!Guten Tag World!Guten Tag World!

PHP Array

• An array stores multiple values in one single variable:

• An array is a special variable, which can hold more than one value
at a time.

• An array can hold many values under a single name, and you can
access thevalues by referring to an index number.

Example

<html>

<body>

<?php

$cars = array("Volvo", "BMW", "Toyota");

echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";

?>
</body>

</html>

OUTPUT:

I like Volvo, BMW and Toyota.

Create an Array in PHP

• In PHP, the array() function is used to create an array:

array();

In PHP, there are three types of arrays:

 Indexed arrays - Arrays with a numeric index


 Associative arrays - Arrays with named keys
 Multidimensional Array - Arrays containing one or more
arrays

Indexed arrays - Arrays with a numeric index


Array identifiers look like normal variable assignments except a pair of
square brackets ([]) are added after the name of the array variable. You
can optionally add an index value between the brackets. If you don’t
supply an index, PHP automatically
picks the lowest empty numeric index value for the array.
<?php
$weekdays[] = 'Monday';
$weekdays[] = 'Tuesday';
?>

You could also specify the index values, which would have the same end
result as the
following:
<?php
$weekdays[0] = 'Monday';
$weekdays[1] = 'Tuesday';
?>

Using the array function to create an array of weekdays

<?php
$weekdays = array('Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
'Sunday');
?>

Associative arrays are arrays that use named keys that


you assign to them.

<!DOCTYPE html>
<html>
<body>

<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>
</body></html>

Output:

Peter is 35 years old.

<?php

$array =
array('Hello','first','nice','loost','emy','rood',1599,34345,1313,45667,5
678,35546,8877,3434,56767,7778,9987,8842,1223);

$i = 0 ;

foreach($array as $key=>$value)
{ if($i <10)
{
echo $value.'<br/>';
}
$i++;
}
?>

Output:
Hello
first
nice
loost
emy
rood
1599
34345
1313
45667

Multidimensional arrays - Arrays containing one or more arrays

<!DOCTYPE html>
<html>
<body>

<?php
$cars = array (
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);

echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0]


[2].".<br>";
echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1]
[2].".<br>";
echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2]
[2].".<br>";
echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3]
[2].".<br>";
?>

</body>
</html>

Output:
Volvo: In stock: 22, sold: 18.
BMW: In stock: 15, sold: 13.
Saab: In stock: 5, sold: 2.
Land Rover: In stock: 17, sold: 15.

Looping through and referencing array values


Items in an array may be individually accessed by including the key
to the array inbrackets ([]) after the name of the variable in the form
$array[index].
Arrays referencedin a string that have a key value with whitespaces
or punctuation must beenclosed in curly braces ({}).

<?php
$shapes = array('Soda can' => 'Cylinder',
'Notepad' => 'Rectangle',
'Apple' => 'Sphere',
'Orange' => 'Sphere',
'Phonebook' => 'Rectangle');
print "A notepad is a {$shapes['Notepad']}.";
?>

Output:
A notepad is a Rectangle.

foreach loop displays all the values in an array. The foreach


statementreads each value from an arrayuntil it reaches the last
value n in the array.
Displaying the contents of an array using a loop

<?php
$shapes = array('Soda can' => 'Cylinder',
'Notepad' => 'Rectangle',
'Apple' => 'Sphere',
'Orange' => 'Sphere',
'Phonebook' => 'Rectangle');
foreach ($shapes as $key => $value) { # every associative array has
$key and $value pairs
print "The $key is a $value.<br />";
}
?>

Output:
The Soda can is a Cylinder.
The Notepad is a Rectangle.
The Apple is a Sphere.
The Orange is a Sphere.
The Phonebook is a Rectangle.

Counting how many elements are in an array


count function to find out how many elements are currently assigned
to an array. The count function is identical to sizeof and can be used
interchangeably.

<?php
$shapes = array('Soda can' => 'Cylinder',
'Notepad' => 'Rectangle',
'Apple' => 'Sphere',
'Orange' => 'Sphere',
'Phonebook' => 'Rectangle');
$numElements = sizeof($shapes);
$num = count($shapes);

print "The array has $numElements elements, yes $num.<br />";


?>

Output
The array has 5 elements, yes 5.

Sorting arrays
The sort( ) function sorts an array. Elements are arranged from
lowest to highestafter this function is completed. Numbers are sorted
numerically, while strings aresorted alphabetically. This function
assigns new keys for the elements in an array.
Itremoves any existing keys you may have assigned, rather than just
reordering thekeys.

<?php
$shapes = array("rectangle", "cylinder", "sphere");
sort($shapes);
//The foreach loop selects each element from the array and assigns its
value to $key
//before executing the code in the block.
foreach ($shapes as $key => $value) {
echo "shapes[" . $key . "] = " . $value . "<br />";
}
?>

Output:
shapes[0] = cylinder
shapes[1] = rectangle
shapes[2] = sphere

The shapes have been sorted alphabetically.


Extracting Variables from an Array

The extract function takes anarray as a parameter and creates the


local variables.

<?php
$shapes = array('Sodacan' => 'Cylinder',
'Notepad' => 'Rectangle',
'Apple' => 'Sphere',
'Orange' => 'Sphere',
'Phonebook' => 'Rectangle');
extract($shapes);
// $Sodacan, $Notepad, $Apple, $Orange, and $Phonebook are now
set
echo $Apple;
echo "<br />";
echo $Notepad;
?>

Output:
Sphere
Rectangle

Using compact to build an array from variables

The compact function is the complement of extract. It takes the


variables as parametersindividually, as arrays, or as a combination
of both. The compact function createsan associative array whose keys
are the variable names and whose values are the variable’s value.

Ex:1

<?php
$SodaCan = 'Cylinder';
$NotePad = 'Rectangle';
$Apple = 'Sphere';
$Orange = 'Sphere';
$PhoneBook = 'Rectangle';
$shapes = compact('SodaCan', 'NotePad', 'Apple', 'Orange',
'PhoneBook');
var_dump($shapes);
?>
Output:
array(5) { ["SodaCan"]=> string(8) "Cylinder" ["NotePad"]=> string(9)
"Rectangle" ["Apple"]=> string(6) "Sphere" ["Orange"]=> string(6) "Sphere"
["PhoneBook"]=> string(9) "Rectangle" }

Array Functions in PHP


Reset(array)

Takes an array as its argument and resets the pointer to the


beginning of thearray.

Array_push(array,elements)
Adds one or more elements to the end of an existing array. For
example, array_push($shapes,"rock","paper","scissors"); adds
those three elements to anarray called $shapes.

Array_pop(array)
Returns and removes the last element of an array. For example,
$last_element=array_pop($shapes); removes the last element from
$shapes and assignsit to $last_element.

Array_unshift(array,elements)
Adds one or more elements to the beginning of an existing array. For
example,array_unshift($shapes,"rock","paper","scissors"); adds
three elements to thebeginning of an array called $shapes.

Array_shift(array)Returns and removes the first element of an array.


For example, $first_element=array_unshift($shapes); removes the
first element from $shapes andassigns it to $first_element.

Array_merge(array,array)
Combines two arrays together and returns the new array. For
example,$combined_array=array_merge($shapes,$sizes); combines
the elements of botharrays and assigns the new array to
$combined_array.

Array_keys(array)
Returns an array containing all of the keys fromthe supplied array.
For example, $keys=array_keys($shapes); assigns an array to $keys
that consists of onlythe keys such as "Apple" and "Notepad" from
the array in Example 1.

Array_values(array)
Returns a numerically indexed array containing all of the values
from the supplied array. For example,
$values=array_values($shapes); assigns an array to$values that
consists of only the element values such as "Sphere" and"Rectangle"
from the array in Example 1.

Shuffle(array)
Resorts the array in randomorder. The key values are lost when the
array isshuffled because the returned array is a numeric array. For
example,shuffle($shapes); could place the value "Rectangle" in
$shapes[0] using thearray from Example 1.

Data base design


Database design is the organization of data according to a database
model. The designer determines what data must be stored and how
the data elements interrelate.

Relational Databases
MySQL is a relational database. An important feature of relational
systems is that data can be spread across several tables Related data
is stored in separate tables and allows you to put them together by
using a key common to both tables. The key is the relation between
the tables.
The most important concept that you need to understand is that you
must ensure that the selected key is unique. If it’s possible that two
records (past, present, or future) share the same value for an
attribute, don’t use that attribute as a primary key. Including key
fields fromanother table to forma link between tables is called a
foreign key relationship, like a boss to employees or a user to a
purchase.

Relationship Types
Databases relationships are quantified with the following categories:
• One-to-one relationships
• One-to-many relationships
• Many-to-many relationships
One-to-One Relationship
Under One-to-One (1:1) relationship, an instance of entity P is
related to instance of entity Q and an instance of entity Q is related to
instance of entity P.

Let us see an example −

A person can have only one passport, and a passport is assigned to a


single person.
One-to-Many Relationship
Under One-to-Many (1:N) relationship, an instance of entity P is
related to more than one instance of entity Q and an instance of
entity Q is related to more than one instance of entity P.

Let us see an example −

A Person can have more than one Bank Accounts but a bank account
can have at most one person as account holder.

Many-to-Many Relationship
Under Many-to-Many (N:N) relationship, more than one instance of
entity P is related to more than one instance of entity Q. For more
than one instance of entity Q is related to more than one instance of
entity P.

Let us see an example –

A person can have more than one skills. More than one person can
attain a skill.

Normalization:
o Normalization is the process of organizing
the data in the database.
o Normalization is used to minimize the
redundancy from a relation or set of
relations. It is also used to eliminate
undesirable characteristics like Insertion,
Update, and Deletion Anomalies.
o Normalization divides the larger table into
smaller and links them using relationships.
o The normal form is used to reduce
redundancy from the database table.
The main reason for normalizing the relations is
removing these anomalies.
Failure to eliminate anomalies leads to data
redundancy and can cause data integrity and
other problems as the database grows.
Normalization consists of a series of guidelines
that helps to guide you in creating a good
database structure.
Data modification anomalies can be
categorized into three types:

o Insertion Anomaly: Insertion Anomaly


refers to when one cannot insert a new
tuple into a relationship due to lack of data.
o Deletion Anomaly: The delete anomaly
refers to the situation where the deletion of
data results in the unintended loss of some
other important data.
o Updatation Anomaly: The update
anomaly is when an update of a single data
value requires multiple rows of data to be
updated.

First Normal Form (1NF)


o A relation will be 1NF if it contains an
atomic value.
o It states that an attribute of a table cannot
hold multiple values. It must hold only
single-valued attribute.
o First normal form disallows the multi-valued
attribute, composite attribute, and their
combinations.
Example: Relation EMPLOYEE is not in 1NF
because of multi-valued attribute EMP_PHONE.
EMPLOYEE table:
EMP_I EMP_NA EMP_P EMP_STAT
D ME HONE E

14 John 727282 UP
6385,
906473
8238

20 Harry 857478 Bihar


3832

12 Sam 739037 Punjab


2389,
858983
0302

The decomposition of the EMPLOYEE table into


1NF has been shown below:

EMP_ID EMP_NAME EMP_PHONE EMP_STATE

14 John 7272826385 UP
14 John 9064738238 UP

20 Harry 8574783832 Bihar

12 Sam 7390372389 Punjab

12 Sam 8589830302 Punjab

Second Normal Form (2NF)


o In the 2NF, relational must be in 1NF.
o In the second normal form, all non-key
attributes are fully functional dependent on
the primary key
Example: Let's assume, a school can store the
data of teachers and the subjects they teach. In
a school, a teacher can teach more than one
subject.
TEACHER table

TEACHER_I SUBJECT TEACHER_AGE


D
25 Chemistry 30

25 Biology 30

47 English 35

83 Math 38

83 Computer 38

In the given table, non-prime attribute


TEACHER_AGE is dependent on TEACHER_ID
which is a proper subset of a candidate key.
That's why it violates the rule for 2NF.
To convert the given table into 2NF, we
decompose it into two tables:
TEACHER_DETAIL table:

TEACHER_ID TEACHER_AGE

25 30
47 35

83 38

TEACHER_SUBJECT table:

TEACHER_ID SUBJECT

25 Chemistry

25 Biology

47 English

83 Math

83 Computer
Third Normal Form (3NF)
o A relation will be in 3NF if it is in 2NF and
not contain any transitive partial
dependency.
o 3NF is used to reduce the data duplication.
It is also used to achieve the data integrity.
o If there is no transitive dependency for non-
prime attributes, then the relation must be
in third normal form.
A relation is in third normal form if it holds
atleast one of the following conditions for every
non-trivial function dependency X → Y.

1. X is a super key.
2. Y is a prime attribute, i.e., each element of
Y is part of some candidate key.
Example:
EMPLOYEE_DETAIL table:

EMP_ID EMP_NAME EMP_ZIP EMP_STATE EMP_CITY

222 Harry 201010 UP Noida


333 Stephan 02228 US Boston

444 Lan 60007 US Chicago

555 Katharine 06389 UK Norwich

666 John 462007 MP Bhopal

Super key in the table above:

1.{EMP_ID}, {EMP_ID, EMP_NAME}, {EMP_ID, EMP_N


AME, EMP_ZIP}....so on
Candidate key: {EMP_ID}
Non-prime attributes: In the given table, all
attributes except EMP_ID are non-prime.
Here, EMP_STATE & EMP_CITY dependent on EMP_ZIP
and EMP_ZIP dependent on EMP_ID. The non-prime
attributes (EMP_STATE, EMP_CITY) transitively
dependent on super key(EMP_ID). It violates the rule
of third normal form.
That's why we need to move the EMP_CITY and
EMP_STATE to the new <EMPLOYEE_ZIP> table, with
EMP_ZIP as a Primary key.
EMPLOYEE table:
EMP_ID EMP_NAME EMP_ZIP

222 Harry 201010

333 Stephan 02228

444 Lan 60007

555 Katharine 06389

666 John 462007

EMPLOYEE_ZIP table:

EMP_ZIP EMP_STATE EMP_CITY

201010 UP Noida

02228 US Boston
60007 US Chicago

06389 UK Norwich

462007 MP Bhopal

Column Data Types – MYSQL Datatypes

Structured Query Language (SQL)


Structured Query Language (SQL) is a standardized programming language
that is used to manage relational databases and perform various operations on
the data in them.
SQL is used for the following:
 modifying database table and index structures;
 adding, updating and deleting rows of data; and
 retrieving subsets of information from within relational database
management systems (RDBMSes) -- this information can be used for
transaction processing, analytics applications and other applications that
require communicating with a relational database.

SQL queries and other operations take the form of commands written as
statements and are aggregated into programs that enable users to add, modify
or retrieve data from database tables.

A table is the most basic unit of a database and consists of rows and columns of
data. A single table holds records, and each record is stored in a row of the
table. Tables are the most used type of database objects, or structures that
hold or reference data in a relational database.

Other types of database objects include the following:

Views are logical representations of data assembled from one or more


database tables.
Indexes are lookup tables that help speed up database lookup functions.
Reports consist of data retrieved from one or more tables, usually a subset of
that data that is selected based on search criteria.
Each column in a table corresponds to a category of data -- for example,
customer name or address -- while each row contains a data value for the
intersecting column.

Relational databases are relational because they are composed of tables that
relate to each other. For example, a SQL database used for customer service
can have one table for customer names and addresses and other tables that
hold information about specific purchases, product codes and customer
contacts. A table used to track customer contacts usually uses a unique
customer identifier called a key or primary key to reference the customer's
record in a separate table used to store customer data, such as name and
contact information.

SQL commands are divided into several different types, including the
following:

Data Definition Language (DDL) commands are also called data definition
commands because they are used to define data tables.
Data Manipulation Language (DML) commands are used to manipulate data
in existing tables by adding, changing or removing data. Unlike DDL
commands that define how data is stored, DML commands operate in the
tables defined with DDL commands.
Data Query Language consists of just one command, SELECT, used to get
specific data from tables. This command is sometimes grouped with the DML
commands.
Data Control Language commands are used to grant or revoke user access
privileges.
Transaction Control Language commands are used to change the state of some
data -- for example, to COMMIT transaction changes or to ROLLBACK
transaction changes.

SQL syntax, the set of rules for how SQL statements are written and
formatted, is similar to other programming languages. Some components of
SQL syntax include the following:

SQL statements start with a SQL command and end with a semicolon (;), for
example:

SELECT * FROM customers;

This SELECT statement extracts all of the contents of a table called customers.
SQL statements are case-insensitive, meaning that they can be written using
lowercase, uppercase or a combination. However, it is customary to write out
SQL keywords -- commands or control operators -- in all-caps and
table/column names in lowercase. Words in the statement can be treated as
case-sensitive using quotes, so the following two statements produce identical
results.

SELECT * FROM customers;


select * from CUSTOMERS;

These two statements are different:

SELECT * FROM customers;


SELECT * FROM "Customers";

SQL statements are terminated only by the semicolon, meaning that more
complex statements can be rendered across multiple lines, like this one:

SELECT name, telephone, age


FROM customers;
This command selects the contents of the columns name, telephone and age in
the table customers.
SQL statements can incorporate program flow controls, meaning that a
statement can incorporate table and row selection -- as in the previous example
-- and then operate on the data contained in those columns. For example, the
following command selects the name, telephone number and birthdate for all
customers whose age is over 21:

SELECT name, telephone, age


FROM customers
WHERE age > 21;

Most SQL implementations include support for issuing statements at the


command line, through a graphical user interface, by using SQL programs or
through application programming interfaces to access SQL databases using
other programming languages.

Commonly used SQL commands with examples

Most SQL commands are used with operators to modify or reduce the scope of
data operated on by the statement. Some commonly used SQL commands,
along with examples of SQL statements using those commands, follow.

SQL SELECT. The SELECT command is used to get some or all data in a
table. SELECT can be used with operators to narrow down the amount of data
selected:

SELECT title, author, pub_date


FROM catalog
WHERE pub_date = 2021;
This example could be used by a publisher to select the title, author and
publication date columns from a table named catalog.

SQL CREATE. The CREATE command is used to create a new SQL database
or SQL table. Most versions of SQL create a new database by creating a new
directory, in which tables and other database objects are stored as files.

The following CREATE DATABASE statement creates a new SQL database


named Human_Resources:

CREATE DATABASE Human_Resources;

The CREATE TABLE command is used create a table in SQL. The following
statement creates a table named Employees that has three columns:
employee_ID, last_name and first_name, with the first column storing integer
(int) data and the other columns storing variable character data of type
varchar and a maximum of 255 characters.
CREATE TABLE Employees (
employee_ID int,
last_name varchar(255),
first_name varchar(255)
);

SQL DELETE. The DELETE command removes rows from a named table. In
this example, all records of employees with the last name Smithee are deleted:

DELETE FROM Employees WHERE last_name='Smithee';


This statement returns the number of rows deleted when it finishes running.

SQL INSERT INTO. The INSERT INTO command is used to add records into
a database table. The following statement adds a new record into the
Employees table:

INSERT INTO Employees (


last_name,
first_name
)
VALUES (
'Alan',
'Smithee'
);

SQL UPDATE. The UPDATE command is used to make changes to rows or


records in a specific table. For example, the following statement updates all
records that include a last_name value of Smithee by changing the name to
Smith:

UPDATE Employees
SET last_name = 'Smith',
WHERE last_name = 'Smithee';

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy