KEMBAR78
Chapter 1 Introduction To PHP | PDF | World Wide Web | Internet & Web
0% found this document useful (0 votes)
23 views91 pages

Chapter 1 Introduction To PHP

The document provides an introduction to web techniques, covering HTML, CSS, and PHP basics. It explains HTML elements, attributes, forms, and lists, along with CSS syntax and the box model. The document serves as a foundational guide for creating and styling web pages.

Uploaded by

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

Chapter 1 Introduction To PHP

The document provides an introduction to web techniques, covering HTML, CSS, and PHP basics. It explains HTML elements, attributes, forms, and lists, along with CSS syntax and the box model. The document serves as a foundational guide for creating and styling web pages.

Uploaded by

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

1.

Introduction to web techniques


[10]

1.1 Overview of HTML and Basic Tags :-


Creating Forms ,Tables, HTML5 Semantics.
1.2 CSS basic concept
Three ways to use CSS, Box Model, Navigation Bar
1.3 HTTP basics .
1.4 Introduction to Web server and Web browser .
1.5 PHP Basics: Use of PHP, Lexical structure, Language basics
What is HTML?
 HTML stands for Hyper Text Markup Language
 HTML is the standard markup language for creating Web pages
 HTML describes the structure of a Web page
 HTML consists of a series of elements
 HTML elements tell the browser how to display the content
HTML Elements

 The HTML element is everything from the start tag to the end tag:
 <tagname>Content goes here...</tagname>
 Examples of some HTML elements:
 <h1>My First Heading</h1>
 <p>My first paragraph.</p>
HTML Attributes

 All HTML elements can have attributes


 Attributes provide additional information about elements
 Attributes are always specified in the start tag
 Attributes usually come in name/value pairs like: name="value“

HTML Comment Tag


 We can add comments to your HTML source by using the following syntax:
 <! - - This is a comment -->

<p>This is a paragraph.</p>
HTML Tables
HTML tables allow web developers to arrange data into rows and columns.

Each table cell is defined by a <td> and a </td> tag.


td stands for table data.
tr stands for table row.

 <table>
<tr>
<td>Emil</td>
<td>Tobias</td> O/P:
<td>Linus</td> Emil Tobias Linus
</tr> 16 14 10
<tr>
<td>16</td>
<td>14</td>
<td>10</td>
</tr>
</table>
Rowspan & Colspan
 To make a cell span over multiple rows,
use the rowspan attribute
 <table>
 <tr>
 <th>Name</th>
 <td>Jill</td>
 </tr>
 <tr>
 <th rowspan="2">Phone</th>
 <td>555-1234</td>
 </tr>
 <tr>
 <td>555-8745</td>
 </tr>
 </table>
 Toell span over multiple columns, use
the colspan attribute:
 <table>
 <tr>
 <th colspan="2">Name</th>
 <th>Age</th>
 </tr>
 <tr>
 <td>Jill</td>
 <td>Smith</td>
 <td>43</td>
 </tr>
 <tr>
 <td>Eve</td>
 <td>Jackson</td>
 <td>57</td>
 </tr>
Table Example
<html> <td>Paise</td>
<title>Table Example</title> </tr>
<body> </tr>
<h1> Table Example</h1> <tr>

<table border=1> <td>1</td>

<tr> <td>pen</td>

<th rowspan=2>Item no</th> <td>5</td>

<th rowspan=2>Item name</th> <td>50</td>

<th rowspan=2>Item qty</th> <td>00</td>


</tr>
<th colspan=2>Price</th>
</table>
<tr>
</body>
<td>Rs.</td>
</html>
HTML Forms

 An HTML form is used to collect user input. The user input is most often
sent to a server for processing.
 The HTML <form> element is used to create an HTML form for user input

<form>
.
form elements
.
</form>
The <form> element is a container for different types of input elements,
such as: text fields, checkboxes, radio buttons, submit buttons, etc
The HTML <form> Elements

The HTML <form> element can contain one or more of the following
form elements:
•<input>
•<label>
•<select>
•<option>
•<textarea>
•<button>
•<fieldset>
•<legand>
The <input> Element

The HTML <input> element is the most used form element.


An <input> element can be displayed in many ways, depending on the type attribute.

Type Description
<input type="text"> Displays a single-line text input field
<input type="radio"> Displays a radio button (for selecting one of many choices)
<input Displays a checkbox (for selecting zero or more of many
type="checkbox"> choices)
<input type="submit"> Displays a submit button (for submitting the form)
<input type="button"> Displays a clickable button
 <html>
 <body>
 <h1>The input form attribute</h1>
 <form action="page.php“ name="form1">
 <label for="fname">First name:</label>
 <input type="text" id="fname" name="fname"><br><br>
 <label for="lname">Last name:</label>
 <input type="text" id="lname" name="lname" form="form1">
 <input type="submit" value="Submit">
 </form>
 </body>
 </html>
 Radio buttons
<form>
<input type="radio" id="html" name="fav_language"
value="HTML">
<label for="html">HTML</label><br>
<input type="radio" id="css" name="fav_language"
value="CSS">
<label for="css">CSS</label><br>
<input type="radio" id="javascript"
name="fav_language" value="JavaScript">
<label for="javascript">JavaScript</label>
</form>
checkboxes
 <form>
 <input type="checkbox" id="vehicle1" name="vehicle1"
value="Bike">
 <label for="vehicle1"> I have a bike</label><br>
 <input type="checkbox" id="vehicle2" name="vehicle2"
value="Car">
 <label for="vehicle2"> I have a car</label><br>
 <input type="checkbox" id="vehicle3" name="vehicle3"
value="Boat">
 <label for="vehicle3"> I have a boat</label>
 </form>
HTML List
 Unordered HTML List
 An unordered list starts with the <ul> tag. Each list item starts with the
<li> tag.
 The list items will be marked with bullets (small black circles) by default:
<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
o/p:-An unordered HTML list
• Coffee
• Tea
• Milk
Ordered HTML List
An ordered list starts with the <ol> tag. Each list item starts with the <li> tag.
The list items will be marked with numbers by default:
An ordered HTML list
<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
1. Coffee
2. Tea
3. Milk
HTML Description Lists
 A description list is a list of terms, with a description of each term.
 The <dl> tag defines the description list, the <dt> tag defines the term (name),
and the <dd> tag describes each term:
 <dl>
<dt>Coffee</dt>
<dd>- black hot drink</dd>
<dt>Milk</dt>
<dd>- white cold drink</dd>
</dl>
o/p:-
A Description List
Coffee
- black hot drink
Milk
- white cold drink
HTML Frame
 HTML Frames are a powerful tool for dividing your web browser window
into multiple sections, each capable of loading content independently.
This is achieved using a collection of frames within a frameset tag.
 <html>
 <head>
 <title>Example of HTML Frames using row attribute</title>
 </head>
 <frameset rows = "20%, 60%, 20%">
 <frame name = "top" src =
 "C:/Users/dharam/Desktop/attr1.png" />
 <frame name = "main" src =
 "C:/Users/dharam/Desktop/gradient3.png" />
 <frame name = "bottom" src =
 "C:/Users/dharam/Desktop/col_last.png" />
 </frameset>
 </html>
What are Semantic Elements?
A semantic element clearly describes its meaning to
both the browser and the developer.

Examples of semantic elements:


<form>, <table>, and <article> - Clearly defines its
content.

Examples of non-semantic elements:


<div> and <span> - Tells nothing about its content.
CSS

 CSS stands for Cascading Style Sheets


 CSS describes how HTML elements are to be
displayed on screen, paper, or in other media
 CSS saves a lot of work. It can control the
layout of multiple web pages all at once
 External stylesheets are stored in CSS files
CSS Syntax
 A CSS rule consists of a selector and a declaration block.

 . The selector points to the HTML element you want to style.


 The declaration block contains one or more declarations separated
by semicolons.
 Each declaration includes a CSS property name and a value,
separated by a colon.
 Multiple CSS declarations are separated with semicolons, and
declaration blocks are surrounded by curly braces
Example of Element Selector
 In this example all <p> elements will be center-aligned, with a red text color:
 <html>
 <head>
 <style>
 p { color: red;
 text-align: center;}
 </style>
 </head>
 <body>
 <p>Hello World!</p>
 <p>These paragraphs are styled with CSS.</p>
 </body>
 </html>

 O/P: - Hello World!


 These paragraphs are styled with CSS.
The CSS id Selector

 The id selector uses the id attribute of an HTML


element to select a specific element.
 The id of an element is unique within a page, so the id
selector is used to select one unique element!
 To select an element with a specific id, write a hash
(#) character, followed by the id of the element.
 <html>
 <head>
 <style>
 #para1 {
 text-align: center;
 color: red;
 }
 </style>
 </head>
 <body>
 <p id="para1">Hello World!</p>
 <p>This paragraph is not affected by the style.</p>
 </body>
 </html>
The CSS class Selector

 The class selector selects HTML elements with a


specific class attribute.

 To select elements with a specific class, write a period


(.) character, followed by the class name.
 <html>
 <head>
 <style>
 .center {
 text-align: center;
 color: red;
 }
 </style>
 </head>
 <body>
 <h1 class="center">Red and center-aligned heading</h1>
 <p class="center">Red and center-aligned paragraph.</p>
 </body>
 </html>
The CSS Universal Selector
 The universal selector (*) selects all HTML elements
on the page.
 Example
 The CSS rule below will affect every HTML element on
the page:
 <html>
 <head>
 <style>
 *{
 text-align: center;
 color: blue;
 }
 </style>
 </head>
 <body>
 <h1>Hello world!</h1>
 <p>Every element on the page will be affected by the style.</p>
 <p id="para1">Me too!</p>
 <p>And me!</p>
 </body></html>
3 ways to use CSS File
CSS can be added to HTML documents in 3 ways:
•Inline - by using the style attribute inside HTML elements
•Internal - by using a <style> element in the <head> section
•External - by using a <link> element to link to an external CSS file
The most common way to add CSS, is to keep the styles in external CSS files.

Inline CSS
An inline CSS is used to apply a unique style to a single HTML element.
An inline CSS uses the style attribute of an HTML element.
The following example sets the text color of the <h1> element to blue, and the text color
of the <p> element to red:

Example
<h1 style="color:blue;">A Blue Heading</h1>

<p style="color:red;">A red paragraph.</p>


Internal CSS

An internal CSS is used to define a style for a single HTML page.


An internal CSS is defined in the <head> section of an HTML page, within a <style> element.
The following example sets the text color of ALL the <h1> elements (on that page) to blue,
and the text color of ALL the <p> elements to red. In addition, the page will be displayed with
a "powderblue" background color: <html>
ex: <head>
<style>
body {background-color: powderblue;}
h1{color: blue;}
p {color: red;}
</style>
</head>
<body>

<h1>This is a heading</h1>
<p>This is a paragraph.</p>

</body>
</html>
External CSS

An external style sheet is used to define the style for many HTML pages.
To use an external style sheet, add a link to it in the <head> section of each HTML page:
<html>
<head>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>

"styles.css":
body {
background-color: powderblue;}
h1 { color: blue;}
p { color: red;}
Box Model

 In CSS, the term "box model" is used when talking about design and layout.
 The CSS box model is essentially a box that wraps around every HTML element.
It consists of: margins, borders, padding, and the actual content. The image below
illustrates the box model:
 Explanation of the different parts:

 Content - The content of the box, where text and


images appear
 Padding - Clears an area around the content. The
padding is transparent
 Border - A border that goes around the padding and
content
 Margin - Clears an area outside the border. The
margin is transparent
 The box model allows us to add a border around
elements, and to define space between elements.
 <html>
 <head><style>
 div {
 background-color: lightgrey;
 width: 300px;
 border: 15px solid green;
 padding: 50px;
 margin: 20px;
 } </style>
 </head>
 <body>
 <h2>Demonstrating the Box Model</h2>
 <p>The CSS box model is essentially a box that wraps around every HTML element.
It consists of: borders, padding, margins, and the actual content.</p>
 <div>This text is the content of the box. We have added a 50px padding, 20px
margin and a 15px green border. Ut enim ad minim veniam, quis nostrud
exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt
mollit anim id est laborum.</div>
 </body>
CSS Navigation Bar

 Having easy-to-use navigation is important for any web site.


 With CSS you can transform boring HTML menus into good-looking
navigation bars.
 Navigation Bar = List of Links
 A navigation bar needs standard HTML as a base.
 In our examples we will build the navigation bar from a standard HTML list.
 A navigation bar is basically a list of links, so using the <ul> and <li>
elements makes perfect sense:
Example
<html>
<head>
<style>
ul { list-style-type: none;
margin: 0;
padding: 0;}
</style>
</head>
<body>
<p>In this example, we remove the bullets from the list, and its default padding and
margin.</p>
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#news">News</a></li>
<li><a href="#contact">Contact</a></li>
<li><a href="#about">About</a></li>
</ul>
</body>
HTTP basics, Introduction to Web server and Web
browser

 HTTP
 Hyper Text Tranfer Protocol.
 Known as Stateless Protocol. Because it cannot maintain the
state of the web pages (client)
 This Protocol govern the request of the browser and response
of the server.
 The HTTP functions allows you to manipulate information
sent to the browser by the web server,before any other
output has been sent
Some PHP HTTP functions are
Header ()-sends a raw HTTP header to the client
Setcookie()-Sends an HTTP cookie to the client
Web browser
 Definition: A web browser is a software application for
retrieving ,presenting ,and traversing information resources on the
World Wide Web
 Browsers are primarily used to access to WWW but they can also be
used to access information provided by Web Servers.
 The primary purpose of a web browser is to bring information
resources to the user.
 Examples of web browsers:
 HotJava
 Netscape Navigator
 Internet Explorer
 Mozila Firefox
Web server
 Definition: A web server is a computer program that sends (serves)
content, such as web pages ,using HTTP ,over WWW.
 The primary function of a web server is to deliver web pages to
clients(web browser).
 Many generic web servers also support server side scripting lang.
 e.g. Apache Server supports PHP.
 Examples of Web Servers:
 IIS(Microsoft’s Internet Information Server)
 Apache Server.
Scripting Language
 A programming language in which programs are a series of
commands that are interpreted and then executed one by one.The
programs do not need to compiled.

 Client side scripting Language: is a script that is executed by the


browser that resides at the user computer
 E.g.Java script , VB script

 Server side scripting : is a script executed by the server(Web


Server),and the page that is sent to the browser is produced by the
server- side scripting
 e.g. . ASP. Net, ASP,JSP,PHP,Ruby etc.
Brief History of PHP
 PHP originally stood for “Personal Home Page” was first designed
by Ramus Lerdorf in 1994 to track the visitors to his online resume.
 PHP is a popular general-purpose scripting language that is
especially suited to web development
 PHP/FI (Personal Home Page/Forms Interpreter) could be used to
build simple, dynamic web applications. To accelerate bug reporting
and improve the code.
 Version wise new features are added in PHP
 Latest PHP 8.4 was released on 21 Nov. 2024 Having the new
features also supporting old one’s
Introduction to PHP
 Features of PHP
 PHP is an acronym for "PHP: Hypertext Preprocessor"
 PHP is a widely-used, open source scripting language
 PHP scripts are executed on the server
 PHP is free to download and use
 PHP is a Cross Platform Technology
 PHP is HTML Embedded
 PHP is compatible with almost all servers.(Apache,IIS etc.)
 PHP allows tight integration with nearly every database
PHP Prerequisite Tools
 Tools needed for implementing a PHP code:
 A web server application-Apache , IIS
 PHP
 A database application- Postgresql
 A web browser-Microsoft’s IE, Mozilla’s Firefox A text
editor-Windows’s Notepad , Linux’Vi-editor, g-editor
Working of PHP
 PHP is a server side lang.the code you write in PHP sits on a host computer
called a server.The server processes the code and sends web pages to the
requesting visitors
Lexical Structure
 Case Sensitivity
 The names of user defined classes and functions ,as well as built in
constructs and keywords such as echo , while, class, etc. are not
 PHP statements are separated using semicolons.
 Comments
 A comment in PHP code is a line that is not executed as a part of the
program. Its only purpose is to be read by someone who is looking at the
code.
 Comments can be used to:
 Let others understand your code
 Remind yourself of what you did - Most programmers have experienced
coming back to their own work a year or two later and having to re-figure
out what they did. Comments can remind you of what you were thinking
when you wrote the code
Ways of commenting :

 PHP supports several ways of commenting:


 // This is a single-line comment

# This is also a single-line comment

 Multiline comment
 /*
This is a multiple-lines comment block
that spans over multiple
lines
*/
Lexical Structure
 Literals
A literal is a data value that appears directly in a program.
eg: 2001,”Hello World”
 Identifiers
An Identifier is simply a name .In PHP ,identifiers are used to name
variables, functions , constant , and classes
Invalid variables :$not valid, $!
Valid variables : $age, $unit_price
 Constants
A constant is an identifier for a simple value i.e. only scalar values-
Boolean, integer ,double and strings can be constants

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


For e.g.:- define(‘PI’,’3.14’).
Creating (Declaring) PHP Variables

In PHP, a variable starts with the $ sign, followed by the name of the variable:
example
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>
Rules for PHP variables:
•A variable starts with the $ sign, followed by the name of the variable
•A variable name must start with a letter or the underscore character
•A variable name cannot start with a number
•A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and
_)
•Variable names are case-sensitive ($age and $AGE are two different variables)
Remember that PHP variable names are case-sensitive!
Basics of executing PHP code

 PHP files should be saved in the server’s root directory:


 If you are working on windows with WAMP(Windows Apache
MySQL PHP) installed,then save .php files in the wamp server’s
root directory
 “ c:\WAMP\www\abc\hello.php”
 If you are working on Linux, then save .php files in the apache
server’s root directory
 “var/www/html/abc/hello.php”.
 PHP files should have proper extension .php due to which server
treats the script in a special way as a server side script.
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
 <?php
$x = "Hello world!";
$y = 'Hello world!';

echo $x;
echo "<br>";
echo $y;
?>
 O/P : Hello world!
Hello world!
PHP Data Types
 PHP Integer
 An integer data type is a non-decimal number between -2,147,483,648
and 2,147,483,647.
 Example
 <?php
$x = 5985;
var_dump($x);
?>
 O/P: int(5985)
PHP Float

 A float (floating point number) is a number with a decimal point


or a number in exponential form.
 In the following example $x is a float. The PHP var_dump()
function returns the data type and value:
 Example
 <?php
$x = 10.365;
var_dump($x);
?>

 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.
PHP Array

 An array stores multiple values in one single variable.


 In the following example $cars is an array. The PHP var_dump()
function returns the data type and value:
 Example
 <?php
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
?>
o/p
array(3) { [0]=> string(5) "Volvo" [1]=> string(3) "BMW" [2]=> string(6)
"Toyota" }
PHP Object

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


to process that data.
 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:
 <?php
class Car {
function Car() {
$this->model = "VW";
}
}
O/P: VW
// create an object
$herbie = new Car();

// show object properties


echo $herbie->model;
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.
 Tip: 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
 <?php
$x = "Hello world!";
$x = null;
var_dump($x);
?>
 o/p: NULL
PHP Resource
 The special resource type is not an actual data type. It is the
storing of a reference to functions and resources external to
PHP.It is a special variable ,holding a reference to an external
resource.In PHP resource variable can hold anything.
e.g:
 $res=pg_connect(….);
Variable Variables
 You can reference the value of a variable whose name is stored
in another variable.
 Variable variables are simply variables whose names are
dynamically created by another variable’s value.
 for eg.
$rain=‘water’;
$$rain=‘ponds’;
Print $water;

 O/P:-ponds
Operators In PHP
 What is Operator? Simple answer can be given using
expression 4 + 5 is equal to 9. Here 4 and 5 are called operands
and + is called operator. PHP language supports following type of
operators.
 Arithmetic Operators
 Comparison Operators
 Logical (or Relational) Operators
 Assignment Operators
 Conditional (or ternary) Operators
Precedence of PHP Operators
 Operator precedence determines the grouping of terms in an expression

Category Operator Associativity

Unary ! ++ -- Right to left

Multiplicative */% Left to right

Additive +- Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %= Right to left


Type Juggling(Implicit Casting)

 PHP does not require (or support) explicit type definition in


variable declaration; a variable's type is determined by the
context in which the variable is used. That is to say, if a string
value is assigned to variable $var, $var becomes a string. If an
integer value is then assigned to $var, it becomes an integer.
 The conversion of a value from one type to another is called
casting.This kind of implicit casting is called type juggling in PHP.
 Example:
$var3= $var1 + $var2

Here, if $var1 is an integer. $var2 and $var3 will also be treated
as integers
implicit type casting rules for binary
arithmetic operations
Type of First Type of Second Conversion Performed
Operand Operand

Integer Floating Point The integer is converted to


a floating point number

Integer String The string is converted to a


number, if the value after
conversion is a floating
point no,the integer is
converted to a floating
point number.

Floating Point String The string is converted to a


floating point number
implicit type casting rules for binary arithmetic operations

 Some other operators have different expectations of their


operands.The string can start with an integer or floating point
number.If no number is found at the start of the string,the
numeric value of that string is 0.If the string contains a period (.)
or upper or lowercase e,evaluating it numerically produces a
floating point number.
 For eg:-
 <?php
 $a=“9Lives”-1;
 echo”$a”;
 ?>
 O/P: 8
Control Flow Statements in PHP

 Conditional statements, such as if/else and


switch,allow a program to execute different pieces of
code,or none at all,depending on some condition.
 Loops such as while and for ,support the repeated
execution of particular code.
The if Statement

The if statement executes some code if one condition is true.


Syntax
if (condition) {
code to be executed if condition is true;
}
For eg:
<?php
$t = date("H");
if ($t < "20") {
echo "Have a good day!";
}
?>

O/P: Have a good day!


PHP - The if...else Statement

The if...else statement executes some code if a condition is true and another
code if that condition is false.
Syntax
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}

Example
Output "Have a good day!" if the current time is less than 20, and "Have a good
night!" otherwise:
<?php
$t = date("H");

if ($t < "20") {


echo "Have a good day!";
} else {
echo "Have a good night!";
PHP - The if...elseif...else Statement
The if...elseif...else statement executes different codes for more than two conditions.
Syntax
if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
code to be executed if first condition is false and this condition is true;
} else {
code to be executed if all conditions are false;
}
Example
<?php
$t = date("H");

if ($t < "10") {


echo "Have a good morning!";
} elseif ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
Output "Have a good morning!" if the current time is less than 10, and "Have a good day!" if the current time is
less than 20. Otherwise it will output "Have a good night!":
The switch statement is used to select one of many blocks of code to
be executed.
Syntax
switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}
This is how it works: First we have a single expression n (most often a variable),
that is evaluated once. The value of the expression is then compared with the
values for each case in the structure. If there is a match, the block of code
associated with that case is executed. Use break to prevent the code from
running into the next case automatically. The default statement is used if no
 example
 <?php
$favcolor = "red";

switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>
 O/P :Your favorite color is red!
PHP Loops

Often when you write code, you want the same block of code to run over and
over again a certain number of times. So, instead of adding several almost equal
code-lines in a script, we can use loops.
Loops are used to execute the same block of code again and again, as long as a
certain condition is true.
In PHP, we have the following loop types:

•while - loops through a block of code as long as the specified condition is true

•do...while - loops through a block of code once, and then repeats the loop as
long as the specified condition is true

•for - loops through a block of code a specified number of times

•foreach - loops through a block of code for each element in an array


The PHP while Loop

The while loop executes a block of code as long as the specified condition is
true.
Syntax
while (condition is true) {
code to be executed;
}
Examples
The example below displays the numbers from 1 to 5:

Example
<?php
$x = 1;

while($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>
The PHP do...while Loop

The do...while loop will always execute the block of code once, it will then check
the condition, and repeat the loop while the specified condition is true.
Syntax
do {
code to be executed;
} while (condition is true);
Examples
The example below first sets a variable $x to 1 ($x = 1). Then, the do while loop will
write some output, and then increment the variable $x with 1. Then the condition is
checked (is $x less than, or equal to 5?), and the loop will continue to run as long as
$x is less than, or equal to 5:

Example
<?php
$x = 1;

do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
The PHP for Loop
 The for loop is used when you know in advance how many times the
script should run.
 Syntax
 for (init counter; test counter; increment counter) {
code to be executed for each iteration;
}
 Parameters:
 init counter: Initialize the loop counter value
 test counter: Evaluated for each loop iteration. If it evaluates to TRUE,
the loop continues. If it evaluates to FALSE, the loop ends.
 increment counter: Increases the loop counter value
 Examples
 The example below displays the numbers from 0 to 10:
 Example
 <?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
The PHP foreach Loop
The foreach loop works only on arrays, and is used to loop through each
key/value pair in an array.
Syntax
foreach ($array as $value) {
code to be executed;
}
For every loop iteration, the value of the current array element is assigned to
$value and the array pointer is moved by one, until it reaches the last array
element.
Examples
The following example will output the values of the given array ($colors):

Example
<?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $value) {
echo "$value <br>";
}
?>
O/P
red
Another Example of foreach

 <?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

foreach($age as $x => $val) {


echo "$x = $val<br>";
}
?>
 O/P :
 Peter = 35
Ben = 37
Joe = 43
PHP Break Statement

You have already seen the break statement used in an earlier chapter of this
tutorial. It was used to "jump out" of a switch statement.
The break statement can also be used to jump out of a loop.
This example jumps out of the loop when x is equal to 4:

Example
<?php
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
break;
}
echo "The number is: $x <br>";
}
?>
O/P
The number is: 0
The number is: 1
The number is: 2
The number is: 3
PHP Continue Statement
The continue statement breaks one iteration (in the loop), if a
specified condition occurs, and continues with the next iteration in
the loop.
This example skips the value of 4:

Example
<?php
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
continue;
}
echo "The number is: $x <br>";
}
?>
PHP date() and time()Function

 Format a local date and time and return the formatted date
strings:
 Example
 <?php
// Prints the day
echo date("l") . "<br>";

// Prints the day, date, month, year, time, AM or PM


echo date("l jS \of F Y h:i:s A");
?>
Parameters
• d - The day of the month (from 01 to 31)
• D - A textual representation of a day (three letters)
• j - The day of the month without leading zeros (1 to 31)
• l (lowercase 'L') - A full textual representation of a day
• N - The ISO-8601 numeric representation of a day (1 for Monday, 7 for Sunday)
• S - The English ordinal suffix for the day of the month (2 characters st, nd, rd or th. Works
well with j)
• w - A numeric representation of the day (0 for Sunday, 6 for Saturday)
• z - The day of the year (from 0 through 365)
• W - The ISO-8601 week number of year (weeks starting on Monday)
• F - A full textual representation of a month (January through December)
• m - A numeric representation of a month (from 01 to 12)
• M - A short textual representation of a month (three letters)
• n - A numeric representation of a month, without leading zeros (1 to 12)
• t - The number of days in the given month
• L - Whether it's a leap year (1 if it is a leap year, 0 otherwise)
• o - The ISO-8601 year number
• Y - A four digit representation of a year
• y - A two digit representation of a year
• a - Lowercase am or pm
• A - Uppercase AM or PM
• B - Swatch Internet time (000 to 999)
• g - 12-hour format of an hour (1 to 12)
• G - 24-hour format of an hour (0 to 23)
• h - 12-hour format of an hour (01 to 12)
• H - 24-hour format of an hour (00 to 23)
• i - Minutes with leading zeros (00 to 59)
• s - Seconds, with leading zeros (00 to 59)
• u - Microseconds (added in PHP 5.2.2)
• e - The timezone identifier (Examples: UTC, GMT, Atlantic/Azores)
• I (capital i) - Whether the date is in daylights savings time (1 if Daylight Savings
Time, 0 otherwise)
• O - Difference to Greenwich time (GMT) in hours (Example: +0100)
• P - Difference to Greenwich time (GMT) in hours:minutes (added in PHP 5.1.3)
• T - Timezone abbreviations (Examples: EST, MDT)
• Z - Timezone offset in seconds. The offset for timezones west of UTC is negative (-43200 to
50400)
• c - The ISO-8601 date (e.g. 2013-05-05T16:34:42+00:00)
• r - The RFC 2822 formatted date (e.g. Fri, 12 Apr 2013 12:01:05 +0200)
• U - The seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)
 and the following predefined constants can also be used (available since PHP 5.1.0):
• DATE_ATOM - Atom (example: 2013-04-12T15:52:01+00:00)
• DATE_COOKIE - HTTP Cookies (example: Friday, 12-Apr-13 15:52:01 UTC)
• DATE_ISO8601 - ISO-8601 (example: 2013-04-12T15:52:01+0000)
• DATE_RFC822 - RFC 822 (example: Fri, 12 Apr 13 15:52:01 +0000)
• DATE_RFC850 - RFC 850 (example: Friday, 12-Apr-13 15:52:01 UTC)
• DATE_RFC1036 - RFC 1036 (example: Fri, 12 Apr 13 15:52:01 +0000)
• DATE_RFC1123 - RFC 1123 (example: Fri, 12 Apr 2013 15:52:01 +0000)
• DATE_RFC2822 - RFC 2822 (Fri, 12 Apr 2013 15:52:01 +0000)
• DATE_RFC3339 - Same as DATE_ATOM (since PHP 5.1.3)
• DATE_RSS - RSS (Fri, 12 Aug 2013 15:52:01 +0000)
• DATE_W3C - World Wide Web Consortium (example: 2013-04-12T15:52:01+00:00)
PHP time() Function

 Return the current time as a Unix timestamp, then format it to a date:


 Example
 <?php
$t=time();
echo($t . "<br>");
echo(date("Y-m-d",$t));
?>
 O/P:
 1595589058
2020-07-24
PHP strtotime() Function

 Parse English textual datetimes into Unix timestamps:


 Example
 <?php
echo(strtotime("now") . "<br>");
echo(strtotime("3 October 2005") . "<br>");
echo(strtotime("+5 hours") . "<br>");
echo(strtotime("+1 week") . "<br>");
echo(strtotime("+1 week 3 days 7 hours 5 seconds") . "<br>");
echo(strtotime("next Monday") . "<br>");
echo(strtotime("last Sunday"));
?>
 O/P
 1589972726
1128297600
1589990726
1590577526
1590861931
1590364800
1589673600
date_default_timezone_get() & date_default_timezone_set()
Function

 The date_default_timezone_get() function returns the default timezone


used by all date/time functions in the script.
<?php
echo date_default_timezone_get();
?>
O/P : UTC
 The date_default_timezone_set() function sets the default timezone used
by all date/time functions in the script.
 date_default_timezone_set(timezone)
 <?php
date_default_timezone_set("Asia/Bangkok");
echo date_default_timezone_get();
?>
 O/P: Asia/Bangkok
PHP date_sunrise() Function

 The date_sunrise() function returns the sunrise time for a specified day
and location.
 <?php
// Lisbon, Portugal:
// Latitude: 38.4 North, Longitude: 9 West
// Zenith ~= 90, offset: +1 GMT

echo("Lisbon, Portugal: Date: " . date("D M d Y"));


echo("<br>Sunrise time: ");
echo(date_sunrise(time(),SUNFUNCS_RET_STRING,38.4,-9,90,1));
?>

 Lisbon, Portugal
 Date: Sat Jul 25 2024
Sunrise time: 06:36
Sunset time: 20:48
date_sunset()
 The date_sunset() function returns the sunset time for a specified
day and location.
 <?php
// Lisbon, Portugal:
// Latitude: 38.4 North, Longitude: 9 West
// Zenith ~= 90, offset: +1 GMT

echo("Lisbon, Portugal: Date: " . date("D M d Y"));


echo("<br>Sunset time: ");
echo(date_sunset(time(),SUNFUNCS_RET_STRING,38.4,-9,90,1));
?>

You might also like