PHP_unit_II_MB
PHP_unit_II_MB
Unit II
Text Output
<html>
<head>
<title>Hello World</title>
</head>
<body>
<?php
/* This is how to do a
of code */
?>
</body>
</html>
Coding Building Blocks
Variables
$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
$age = 30;
?>
Variable types
Variable scope
Global variables.
Static variables.
<?php
function birthday( ){
static $age = 0;
$age = $age + 1;
}
// Set age to 30
$age = 30;
birthday( );
birthday( );
?>
This displays:
Birthday number 1
Birthday number 2
Age: 30
$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.
<?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.
• String
• Integer
• Boolean
• Array
• Object
• NULL
• Resource
PHP String
• 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 example below returns the length of the string "Hello world!":
Example
<html>
<body>
<?php
Echostrlen("Helloworld!"); ?>
</body>
</html>
OUPUT:
12
Example
<html>
<body>
<?php
echostr_word_count("Hello world!");
?>
</body>
</html>
OUPUT:
2
Reverse a String
Example
<html>
<body>
<?php
echostrrev("Hello world!");
?>
</body>
</html>
OUTPUT:
!dlrowolleH
• The example below searches for the text "world" in the string
"Hello world!":
Example
<html>
<body>
<?php
?>
</body>
</html>
OUPUT:
characters in a string.
Example
<html>
<body>
<?php
?>
</body>
</html>
OUPUT:
Hello Dolly!
PHP Integer
2,147,483,647.
?>
Output:
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
?>
Output:
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.
<?php
$name1 = "Bill";
$name2 = "BILL";
$result = strcasecmp($name1, $name2);
if (!$result){
echo "They match.";
}
?>
Output :
They match.
$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.
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
Example
<html>
<body>
<?php
$x = 5985;
var_dump($x);
?>
</body>
</html>
OUTPUT:
int(5985)
PHP Float
Example
<html>
<body>
<?php
$x = 10.365;
var_dump($x);
?>
</body>
</html>
OUTPUT:
float(10.365)
PHP Boolean
$x = true;
$y = false;
Variables
Example
<html>
<body>
<?php
$x = 5; Output:
$y = 10.5;
Hello world!
echo $txt; 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.
carname, total_volume).
• 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";
?>
</body>
</html>
Example
<html>
<body>
<?php
$txt = "W3Schools.com";
?>
</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>
• The scope of a variable is the part of the script where the variable
can be
referenced/used.
• local
• global
• static
Global and Local Scope
Example
<html>
<body>
<?php
$x = 5; // global scope
FunctionmyTest() {
myTest();
$x</p>"; ?>
</body>
</html>
Output:
OUTPUT:
Example
<html>
<body>
<?php
Function myTest() {
$x = 5; // local scope
myTest();
?>
</body>
</html>OUTPUT:
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
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
• 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
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 "This ", "string ", "was ", "made ", "with
multipleparameters.";
</html>
OUTPUT:
PHP is Fun!
Hello world!
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
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!
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
• First we must declare a class of object. For this, we use the class
keyword. A
Example
<html>
<body>
<?php
class Car {
function Car() {
$this->model = "VW";
// create an object
Echo $herbie->model ;
echo "<br>";
echo $honda->model;
?>
</body>
</html>
OUPUT:
VW
VW
• Null is a special data type which can have only one value: NULL.
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
?>
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.
<?php
$name1 = "Bill";
$name2 = "BILL";
if (!$result){
?>
Output:
They match.
Comparison operators
$name1 < $name2 Less Than True, if $name1 is strictly less than
$name2.
Concatenation
<?php
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
echo $str;
?>
Output:
Constants
Syntax
Parameters:
Example
<!DOCTYPE html>
<html>
<body>
<?php
echo GREETING;
?>
</body>
</html>
Output:
Welcome to W3Schools.com!
• Constants do not have a dollar sign ($) at the start of their names.
<?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
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
<?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
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
if ($username == "Admin") {
echo ('Welcome to the admin page.');
}
The curly braces aren’t needed if you want to execute only one statement
if ($username == "Admin"){
echo ('Welcome to the admin page.');
}
else {
echo ('Welcome to the user page.');
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!
For example, you might have avariable called $action, which may have
the values add, modify, and delete
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.";
}
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
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
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;
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.
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.
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!";
}
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));
<?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
function sum(int $x, int $y) {
$z = $x + $y;
return $z;
}
Output:
5 + 10 = 15
7 + 13 = 20
2+4=6
{
return $a + $b;
}
echoaddNumbers(1.2, 5.2);
?>
Output:
6.4
<?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
Output:
4
Output:
4
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"
?>
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:
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
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
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;
}
}
echo $apple->get_name();
echo "<br>";
echo $banana->get_name();
?>
Output:
Green Apple
Yellow Banana
echo $apple->name;
?>
Output:
Apple
PHP - instanceof
<?php
class Fruit {
public $name;
}
$apple = new Fruit();
var_dump($apple instanceof Fruit);
?>
Output:
bool(true)
Constructor:
<?php
class Fruit {
public $name;
public $color;
function __construct($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
Output
Apple
Destructor:
function __construct($name) {
$this->name = $name;
}
function __destruct() {
echo "The fruit is {$this->name}.";
}
}
Output:
The fruit is Apple.
<?php
class Fruit {
public $name;
protected $color;
private $weight;
}
Output:
Mango
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.
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}.";
}
}
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.
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}.";
}
}
Output
Am I a fruit or a berry? The fruit is Strawberry and the color
is red.
<?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}.";
}
}
$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.
$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.
<?php
final class Fruit {
}
</body>
</html>
Output:
PHP Fatal error: Class Strawberry may not inherit from final
class (Fruit)
<!DOCTYPE html>
<html>
<body>
<?php
class Fruit {
final 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.
parent::method_from_parent
<?php
class Cat {
function eat( ){
echo "Chomp chomp.</br>";
}
function Meow( ){
echo "Meow.</br>";
}
}
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.
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 {
}
functionHypnotic_Cat( ) {
}
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;
Output
Hello World!HelloWorld!Guten Tag World!Guten Tag World!
PHP Array
• 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
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
</body>
</html>
OUTPUT:
array();
You could also specify the index values, which would have the same end
result as the
following:
<?php
$weekdays[0] = 'Monday';
$weekdays[1] = 'Tuesday';
?>
<?php
$weekdays = array('Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
'Sunday');
?>
<!DOCTYPE html>
<html>
<body>
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>
</body></html>
Output:
<?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
<!DOCTYPE html>
<html>
<body>
<?php
$cars = array (
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
</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.
<?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.
<?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.
<?php
$shapes = array('Soda can' => 'Cylinder',
'Notepad' => 'Rectangle',
'Apple' => 'Sphere',
'Orange' => 'Sphere',
'Phonebook' => 'Rectangle');
$numElements = sizeof($shapes);
$num = count($shapes);
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
<?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
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_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_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.
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.
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.
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:
14 John 727282 UP
6385,
906473
8238
14 John 7272826385 UP
14 John 9064738238 UP
25 Biology 30
47 English 35
83 Math 38
83 Computer 38
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:
EMPLOYEE_ZIP table:
201010 UP Noida
02228 US Boston
60007 US Chicago
06389 UK Norwich
462007 MP Bhopal
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.
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:
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.
SQL statements are terminated only by the semicolon, meaning that more
complex statements can be rendered across multiple lines, like this one:
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:
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 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:
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:
UPDATE Employees
SET last_name = 'Smith',
WHERE last_name = 'Smithee';