Sei sulla pagina 1di 62

Introduction to PHP

Define PHP. What these tags specify in PHP <?php and?>

 The Hypertext Preprocessor (PHP) is a scripting language that allows web


developers to create dynamic content that interacts with databases.
 PHP is basically used for developing web based software applications.
 PHP started out as a small open source project that evolved as more and
more people found out how useful it was.
 Rasmus Lerdorf released the first version of PHP way back in 1994.
 PHP is a server side scripting language that is embedded in HTML. It is used
to manage dynamic content, databases, session tracking, even build entire e-
commerce sites.
 It is integrated with a number of popular databases, including MySQL,
PostgreSQL, Oracle, Sybase, Informix, and Microsoft SQL Server.
 PHP supports a large number of major protocols such as POP3(Post Office
Protocol), IMAP(Internet Message Access Protocol), and
LDAP(LightWeight Directory Access Protocol). PHP4 added support for
Java and distributed object architectures (COM and CORBA), making n-
tier development a possibility for the first time.
Currently used in these sites

There are 80% websites are developed using php.


1. Facebook
2. Wikipedia
3. Yahoo
4. Flickr
5. Tumblr
6. Friendster
7. Istockphoto
8. sourceforge .net
9. Wordpress
10.PolicyMantra
Source: W3Techs

What Can PHP Do?


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

With PHP you are not limited to output HTML. You can output images, PDF files, and even Flash movies.
You can also output any text, such as XHTML and XML.

Why PHP ?
 PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
 PHP is compatible with almost all servers used today (Apache, IIS, etc.)
 PHP supports a wide range of databases
 PHP is free. Download it from the official PHP resource: www.php.net
 PHP is easy to learn and runs efficiently on the server side

Common uses of PHP


o PHP performs system functions, i.e. from files on a system it can
create, open, read, write, and close them.
o PHP can handle forms, i.e. gather data from files, save data to a file,
through email you can send data, return data to the user.
o You add, delete, and modify elements within your database through
PHP.
o Access cookies variables and set cookies.
o Using PHP, you can restrict users to access some pages of your
website.
o It can encrypt data.

How does php works


How PHP generates
HTML/JS Web pages
Client
Browser

1 4 PHP
3 module
Apache
2
1: Client from browser send HTTP request (with POST/GET
variables)
2: Apache recognizes that a PHP script is requested and sends the
request to PHP module
3: PHP interpreter executes PHP script, collects script output and
sends it back
4: Apache replies to client using the PHP script output as HTML
output
Characteristics ofPHP OR Features of PHP
The main features of php is; it is open source scripting language so you can free
download this and use. PHP is a server site scripting language. It is open source
scripting language. It is widely used all over the world. It is faster than other scripting
language. Some important features of php are given below;

1. Simple
2. Faster
3. Interpreted
4. Open Source
5. Case Sensitive
6. Simplicity
7. Efficiency
8. Platform Independent
9. Security
10. Flexibility
11. Familiarity
12. Error Reporting
13. Loosely Typed Language
14. Real-Time Access Monitoring
Simple

It is very simple and easy to use, compare to other scripting language, this is widely
used all over the world.

Interpreted

It is an interpreted language, i.e. there is no need for compilation.

Faster

It is faster than other scripting language e.g. asp and jsp.

Open Source

Open source means you do not need to pay for using php, you can free download and
use.

Platform Independent

PHP code will be run on every platform, Linux, Unix, Mac OS X, Windows.

Case Sensitive

PHP is case sensitive scripting language at time of variable declaration. In PHP, all
keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined
functions are NOT case-sensitive.

Error Reporting

PHP have some predefined error reporting constants to generate a warning or error
notice.

Real-Time Access Monitoring

PHP provides access logging by creating the summary of recent accesses for the user.

Loosely Typed Language

PHP supports variable usage without declaring its data type. It will be taken at the
time of the execution based on the type of data it has on its value.
Alternatives to PHP

● Practical extraction and Report Language (Perl)


● Active Server Pages (ASP)
● Java server pages (JSP)
● Ruby

Why PHP is known as scripting language?


 Being a server side language, many people assume that PHP is a purely
programming language. The ability of this language to perform some
complex tasks cements the position of PHP as a programming language.
 However, the truth of the matter is PHP is a powerful scripting language for
web programming. It is the language that you can use to allow a seamless
interaction between web pages and the servers.
 This is one of the factors that differentiate programming and scripting
languages. While programming languages are compiler based, scripting
languages are interpreter based.
 This simply means that PHP doesn’t have to be compiled before interpreted.
The compilation process entails translating a high-level language into a
machine language.
 As a scripting language, PHP doesn’t have to be compiled. Instead, the
interpreter executes the instructions directly without first converting them
into machine instructions.
 This is different from programming languages as they first have to be
compiled into machine language before being interpreted.
 Usage
o Another reason that makes PHP is a purely scripting language is the
usage. This is because PHP must be combined with other languages
and components in order to come up with a complete system.
o This is a typical characteristic of most scripting languages. They
cannot fully depend on themselves to build an application. They must
be blended with other applications. For example, PHP should be
blended with HTML and JavaScript.
 Temperament
o By temperament means to the levels of difficulty of a programming
language.
o It is too hard or can it be easily coded. Scripting languages are very
easy to code. You simply need to type only a few lines of code. This
is another reason why PHP can be easily categorized as a scripting
language.
o On the other hand, programming languages will force you to write
several lines of codes just to implement a single function. You won’t
get away with some short lines codes.
 Interpretation
o As a scripting language, PHP is interpreted within another language
such as HTML before being interpreted again by the browser.
o This is different from programming languages which are compiled
into a compact form and don’t have to be interpreted by another
program.

Getting started with PHP


Set Up PHP
must:

 install a web server(Xamp server)


 install PHP
 install a database, such as MySQL

XAMPP
XAMPP is an open source software developed by Apache friends. XAMPP software
package contains Apache distributions for Apache server, MariaDB, PHP, and Perl. And
it is basically a local host or a local server. This local server works on your own desktop
or laptop computer. The use of XAMPP is to test the clients or your website before
uploading it to the remote web server. This XAMPP server software gives you the
suitable environment for testing MYSQL, PHP, Apache and Perl projects on the local
computer.

The full form of XAMPP is

X stands for Cross-platform

A Apache server,

M MariaDB,

P PHP and

P Perl.
The Cross-platform usually means that it can run on any computer with any
operating system. MariaDB is the most famous database server and it is developed by
MYSQL team. PHP usually provides a space for web development. PHP is a server-side
scripting language. And the last Perl is a programming language and is used to develop a
web application.

The XAMPP installation process is very simple and fast. Once XAMPP is
installed on your local computer it acts as a local server or localhost. You can test the
websites before uploading it to the remote web server. This XAMPP server software
gives you a suitable environment for testing MYSQL, PHP, Apache and Perl
applications on a local computer.

Installation Process for XAMPP on Windows


Step 1

In the web browser, You can easily download XAMPP


from http://www.apachefriends.org/. Since it is an open source you can download it for
free.

Step 2

Once the software is downloaded, you have to install by double click the .exe file

Step 3
Once the file is executed, a setup window appears. In the setup file, select the
components that are required. For eg (if you want to install WordPress on XAMPP, the
required components are MySQL, Apache, PHPMyAdmin).
Step 4

Next step is to choose the folder where the file is to be located. It is recommended to
choose the default “C drive” and then click “Next” button.

Step 5

Clicking on the next your installation process will be started. The setup wizard will
unpack and install all the selected components and will save them to their designated
directory. The installation process takes a couple of minutes to complete.

Step 6
Once the installation process is completed, click on the “Finish” button.
Step 7
Once done, the XAMPP icon will appear on your desktop or start menu. By double-
clicking the XAMPP icon, XAMPP control panel window appears.

Step 8

In the XAMPP control panel, click the necessary modules that are required for you to
work. You can start the modules by clicking the “Start” button under “Actions”. You
will be able to see the initiated modules highlighted in green. For example, if you are
using WordPress platform then the required components are Apache and MYSQL.

Note: If you cannot start a module as a result of the error, then it will be indicated with a
red font. They will provide you with a detailed report to identify the cause of an error.

Step 9

Then by clicking the Apache or any “Admin” button in the XAMPP control panel, you
will be able to configure each module settings separately.

Step 10

That’s it, now in your web browser type localhost and you will be able to see a splash
screen of XAMPP. Here you have to choose a language which you understand.

Can we run PHP from HTML file? If yes, how?


 When building a complex page, at some point you will be faced withthe
need to combine PHP and HTML to achieve your needed results.
 At first point, this can seem complicated, since PHP and HTML aretwo
separate languages, but this is not the case.
 PHP is designed to interact with HTML and PHP scripts can be included in
an HTML page without a problem.
 In an HTML page, PHP code is enclosed within special PHP tags.
 When a visitor opens the page, the server processes the PHP code and then
sends the output (not the PHP code itself) to the visitor's browser.
 Actually it is quite simple to integrate HTML and PHP.
 A PHP script can be treated as an HTML page, with bits of PHP inserted
here and there. Anything in a PHP script that is not contained
within <?php ?> tags is ignored by the PHP compiler and passed directly to
the web browser. If you look at the example below you can see what a full
PHP script might look like:
<head></head>
<body class="page_bg">
Hello, today is <?php echo date('l, F jS, Y'); ?>.
</body>
</html>

 The code above is simply HTML, with just a bit of PHP that prints out
today's date using the built-in date function. As mentioned above, all of the
plain HTML in the code above will be ignored by the PHP compiler and
passed through to the web browser untouched.
 Integrating PHP and HTML is really very simple. Just remember that at its
core, a PHP script is just an HTML page with some PHP sprinkled through
it. If you want, you can create a PHP script that only has HTML in it and
no <?php ?> tags, and it will work just fine.

Write a program in PHP to calculate squareroot of a number

By Using sqrt():
<?php
echo(sqrt(25));
?>

By Longer Method:
<?php
function my_sqrt($n)
{
$x = $n;
$y = 1;
while($x > $y)
{
$x = ($x + $y)/2;
$y = $n/$x;
}
return $x;
}
print(my_sqrt(16)."\n");
?>

Basic PHP Syntax

A PHP script can be placed anywhere in the document.

A PHP script starts with <?php and ends with ?>:

<?php
// PHP code goes here
?>

The default file extension for PHP files is ".php".

A PHP file normally contains HTML tags, and some PHP scripting code.

PHP Variables
A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume).

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)
<?php
$txt = "Hello world!";
$x = 5;
$y = 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 a variable. It is
created the moment you first assign a value to it.

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

List data types and explain


with example.

Data Types in PHP


The values assigned to a PHP variable may be of different data types including
simple string and numeric types to more complex data types like arrays and objects.
PHP supports total eight primitive data types: Integer, Floating point number or
Float, String, Booleans, Array, Object, resource and NULL. These data types are
used to construct variables. Now let's discuss each one of them in detail.

PHP Integers
Integers are whole numbers, without a decimal point (..., -2, -1, 0, 1, 2, ...). Integers
can be specified in decimal (base 10), hexadecimal (base 16 - prefixed with 0x) or
octal (base 8 - prefixed with 0) notation, optionally preceded by a sign (- or +).

The var_dump() function is used to display structured information (type and value)
about one or more variables.
Example
Run this code

<?php
$a = 123; // decimal number
var_dump($a);
echo "<br>"
$b = -123; // a negative number
var_dump($b);
echo "<br>";

$c = 0x1A; // hexadecimal number


var_dump($c);
echo "<br>";

$d = 0123; // octal number


var_dump($d);
?>

Note: Since PHP 5.4+ you can also specify integers in binary (base 2) notation. To
use binary notation precede the number with 0b (e.g. $var = 0b11111111;).

PHP Strings
Strings are sequences of characters, where every character is the same as a byte.
A string can hold letters, numbers, and special characters and it can be as large as
up to 2GB (2147483647 bytes maximum). The simplest way to specify a string is
to enclose it in single quotes (e.g. 'Hello world!'), however you can also use double
quotes ("Hello world!").

Example
Run this code

<?php
$a = 'Hello world!';
echo $a;
echo "<br>";

$b = "Hello world!";
echo $b;
echo "<br>";

$c = 'Stay here, I\'ll be back.';


echo $c;
?>

PHP Floating Point Numbers or Doubles


Floating point numbers (also known as "floats", "doubles", or "real numbers") are
decimal or fractional numbers, like demonstrated in the example below.

Example
Run this code

<?php
$a = 1.234;
var_dump($a);
echo "<br>";

$b = 10.2e3;
var_dump($b);
echo "<br>";
$c = 4E-10;
var_dump($c);
?>

PHP Booleans
Booleans are like a switch it has only two possible values either 1 (true) or 0 (false).

Example
Run this code

<?php
// Assign the value TRUE to a variable
$show_error = true;
var_dump($show_error);
?>

PHP Arrays
An array is a variable that can hold more than one value at a time. It is useful to
aggregate a series of related items together, for example a set of country or city
names.
An array is formally defined as an indexed collection of data values. Each index
(also known as the key) of an array is unique and references a corresponding value.

Example
Run this code

<?php
$colors = array("Red", "Green", "Blue");
var_dump($colors);
echo "<br>";

$color_codes =
array( "Red" =>
"#ff0000",
"Green" => "#00ff00",
"Blue" => "#0000ff"
);
var_dump($color_codes);
?>
You will learn more about arrays in PHP Array tutorial.

PHP Objects
An object is a data type that not only allows storing data but also information on,
how to process that data. An object is a specific instance of a class which serve as
templates for objects. Objects are created based on this template via the new
keyword.
Every object has properties and methods corresponding to those of its parent class.
Every object instance is completely independent, with its own properties and
methods, and can thus be manipulated independently of other objects of the same
class.
Here's a simple example of a class definition followed by the object creation.

Example
Run this code

<?php
// Class definition
class greeting{
// properties
public $str = "Hello World!";

// methods
function
show_greeting(){ return
$this->str;
}
}

// Create object from class


$message = new greeting;
var_dump($message);
?>

Tip: The data elements stored within an object are referred to as its properties and
the information, or code which describing how to process the data is called the
methods of the object.

PHP NULL
The special NULL value is used to represent empty variables in PHP. A variable of
type NULL is a variable without any data. NULL is the only possible value of type
null.

Example
Run this code

<?php
$a = NULL;
var_dump($a);
echo "<br>";

$b = "Hello World!";
$b = NULL;
var_dump($b);
?>
When a variable is created without a value in PHP like $var; it is automatically
assigned a value of null. Many novice PHP developers mistakenly considered
both $var1 = NULL; and $var2 = ""; are same, but this is not true. Both variables
are different — the $var1 has null value while $var2indicates no value assigned to
it.

PHP Resources
A resource is a special variable, holding a reference to an external resource.
Resource variables typically hold special handlers to opened files and database
connections.

Example
Run this code

<?php
// Open a file for reading
$handle = fopen("note.txt", "r");
var_dump($handle);
echo "<br>";

// Connect to MySQL database server with default setting


$link = mysql_connect("localhost", "root", "");
var_dump($link);
?>

PHP 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

ex:

define("PI","3.142",false);

define("PI","3.142",true);

Write a PHP program to calculate area of circle

<?php

define("PI","3.142",false);

$radius="2";

echo "area of a circle ".PI*$radius*$radius;

?>
Explain comments in PHP
 Comments in PHP
o A comment is something which is ignored and not read or executed by
PHP engine or the language as part of a program and is written to
make the code more readable and understandable.
o These are used to help other users and developers to describe the code
and what it is trying to do.
o It can also be used in documenting a set of code or part of a program.
o PHP supports two types of comment:
 Single Line Comment: As the name suggests this is single line
or short relevant explanations that one can add in the code. To
add this, we need to begin the line with (//) or (#).
Example:
<?php

// This is a single line comment

// These cannot be extended to more lines

echo "hello world!!!";

# This is also a single line comment

?>

Output:
hello world!!!

 Multi-line or Multiple-line Comment: These are used to


accommodate multiple lines with a single tag and can be
extended to many lines as required by the user. To add this, we
need to begin and end the line with (/*…*/)
<?php

/* This is a multi-line comment

In PHP variables are written

by adding a $ sign at the beginning.*/

$geek = "hello world!";

echo $geek;

?>

Output:
hello world!

List different operators and explain with examples.


Operators are used to perform operations on variables and values. PHP divides the
operators in the following groups:

 Arithmetic operators
 Assignment operators
 Comparison operators
 Increment/Decrement operators
 Logical operators
 String operators
 Array operators

PHP Arithmetic Operators

The PHP arithmetic operators are used with numeric values to perform common
arithmetical operations, such as addition, subtraction, multiplication etc.
Operator Name Example Result

+ Addition $x + $y Sum of $x and $y

- Subtraction $x - $y Difference of $x and $y

* Multiplication $x* $y Product of $x and $y

/ Division $x / $y Quotient of $x and $y

% Modulus $x % $y Remainder of $x divided by $y

** Exponentiation $x ** $y Result of raising $x to the $y'th power


(Introduced in PHP 5.6)

PHP Assignment Operators

The PHP assignment operators are used with numeric values to write a value toa
variable.

The basic assignment operator in PHP is "=". It means that the left operand gets set
to the value of the assignment expression on the right.
Assignment Same as... Description

x=y x=y The left operand gets set to the value of the
expression on the right

x += y x=x+y Addition

x -=y x=x-y Subtraction

x *=y x=x*y Multiplication

x /=y x=x/y Division

x %= y x=x% y Modulus

PHP Comparison Operators

The PHP comparison operators are used to compare two values (number or string):
Operator Name Example Result

== Equal $x == $y Returns true if $x is equal to $y

=== Identical $x === $y Returns true if $x is equal to $y, and


they are of the same type

!= Not equal $x != $y Returns true if $x is not equal to $y

<> Not equal $x <> $y Returns true if $x is not equal to $y

!== Not identical $x !== $y Returns true if $x is not equal to $y, or


they are not of the same type

> Greater than $x > $y Returns true if $x is greater than $y

< Less than $x < $y Returns true if $x is less than $y

>= Greater than or $x >= $y Returns true if $x is greater than or


equal to equal to $y
<= Less than or $x <= $y Returns true if $x is less than or equal equal to
to $y

<?php
$x = 50;
$y = "500";

var_dump($x === $y); // returns false because types are not equal
?>

PHP Increment / Decrement Operators

The PHP increment operators are used to increment a variable's value. The PHP
decrement operators are used to decrement a variable's value.

Operator Name Description

++$x Pre-increment Increments $x by one, then returns $x

$x++ Post-increment Returns $x, then increments $x by one

--$x Pre-decrement Decrements $x by one, then returns $x

$x-- Post-decrement Returns $x, then decrements $x by one


PHP Logical Operators

The PHP logical operators are used to combine conditional statements.

And And $x and $y True if both $x and $y are true

Or Or $x or $y True if either $x or $y is true

Xor Xor $x xor $y True if either $x or $y is true, but not


both

&& And $x && $y True if both $x and $y are true

|| Or $x || $y True if either $x or $y is true

! Not !$x True if $x is not true

Ex:
<?php
$x = 100;
$y = 50;

if ($x == 100 xor $y == 80) {


echo "Hello world!";
}
?>

PHP String Operators

PHP has two operators that are specially designed for strings.

Operator Name Example Result


. Concatenation $txt1 . $txt2 Concatenation of $txt1 and
$txt2

.= Concatenation $txt1 .= $txt2 Appends $txt2 to $txt1


assignment

PHP Array Operators

The PHP array operators are used to compare arrays.

Operator Name Example Result

+ Union $x + $y Union of $x and $y

== Equality $x == $y Returns true if $x and $y have the same


key/value pairs

=== Identity $x === $y Returns true if $x and $y have the same


key/value pairs in the same order and of
the same types
!= Inequality $x != $y Returns true if $x is not equal to $y

<> Inequality $x <> $y Returns true if $x is not equal to $y

!== Non- $x !== $y Returns true if $x is not identical to $y


identity

PHP Conditional Assignment Operators


The PHP conditional assignment operators are used to set a value depending on conditions:

Operator Name Example Result

?: Ternary $x Returns the value of $x.


= expr1 ? expr2 : The value of $x is expr2 if expr1 =
expr3 TRUE.
The value of $x is expr3 if expr1 =
FALSE

?? Null $x Returns the value of $x.


coalescing = expr1 ?? expr2 The value of $x
is expr1 if expr1 exists, and is not
NULL.
If expr1 does not exist, or is NULL,
the value of $x is expr2.
Introduced in PHP 7
List different loops used in PHP in details
 Like any other language, loop in PHP is used to execute a statement or a
block of statements, multiple times until and unless a specific condition is
met.
 This helps the user to save both time and effort of writing the same code
multiple times.
 PHP supports four types of looping techniques;
o for loop
o while loop
o do-while loop
o foreach loop
 Details of these loops in given below:
1. for loop: This type of loops is used when the user knows in advance, how
many times the block needs to execute. That is, the number of iterations is
known beforehand. These type of loops are also known as entry-controlled
loops. There are three main parameters to the code, namely the initialization,
the test condition and the counter.
Syntax:
for (initialization expression; test condition; update expression) {
// code to be executed
}
In for loop, a loop variable is used to control the loop. First initialize this loop
variable to some value, then check whether this variable is less than or greater
than counter value. If statement is true, then loop body is executed and loop
variable gets updated . Steps are repeated till exit condition comes.
 Initialization Expression: In this expression we have to initialize the
loop counter to some value. for example: $num = 1;
 Test Expression: In this expression we have to test the condition. If
the condition evaluates to true then we will execute the body of loop and
go to update expression otherwise we will exit from the for loop. For
example: $num <= 10;
 Update Expression: After executing loop body this expression
increments/decrements the loop variable by some value. for example:
$num += 2;
Example:
<?php

// code to illustrate for loop


for ($num = 1; $num <= 10; $num += 2)

{ echo "$num \n";} ?>

Flow Diagram:
2. while loop: The while loop is also an entry control loop like for loops i.e., it
first checks the condition at the start of the loop and if its true then it enters
the loop and executes the block of statements, and goes on executing it as long
as the condition holds true.
Syntax:
while (if the condition is true) {
// code is executed
}
Example:
<?php

// PHP code to illustrate while loops

$num = 2;

while ($num < 12) {

$num += 2;

echo $num, "\n";

?>

Flowchart:
3. do-while loop: This is an exit control loop which means that it first enters
the loop, executes the statements, and then checks the condition. Therefore, a
statement is executed at least once on using the do…while loop. After
executing once, the program is executed as long as the condition holds true.
Syntax:
do {
//code is executed
} while (if condition is true);
Example:
<?php

// PHP code to illustrate do...while loops

$num = 2;

do {

$num += 2;

echo $num, "\n";

} while ($num < 12);


?>

Flowchart:

4. foreach loop: This loop is used to iterate over arrays. For every counter of
loop, an array element is assigned and the next counter is shifted to the next
element.
Syntax:
foreach (array_element as value) {
//code to be executed
}
Example:
<?php

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

foreach ($arr as $val) {

echo "$val ";

$na = array ("Ram","Laxman","Sita");

foreach ($na as $val) {

echo "$val ";


}

?>

Output:
10 20 30 40 50 60 Ram Laxman Sita

List different decision making used in PHP in details


PHP allows us to perform actions based on some type of conditions that may be
logical or comparative. Based on the result of these conditions i.e., either TRUE or
FALSE, an action would be performed as asked by the user. It’s just like a two-
way path. If you want something then go this way or else turn that way. To use this
feature, PHP provides us with four conditional statements:

 if statement
 if…else statement
 if…elseif…else statement
 switch statement

Details of each of them is give below:


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

$x = 12;

if ($x > 0) {

echo "The number is positive"; }


?>

Output:
The number is positive
Flowchart:

2. if…else Statement: We understood that if a condition will hold i.e., TRUE,


then the block of code within if will be executed. But what if the condition is
not TRUE and we want to perform an action? This is where else comes into
play. If a condition is TRUE then if block gets executed, otherwise else block
gets executed.
Syntax:
if (condition) {
// if TRUE then execute this code
}
else{
// if FALSE then execute this code
}
Example:
<?php
$x = -12;

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

else{ echo "The number is negative"; }

?>

Output:
The number is negative
Flowchart:

3. if…elseif…else Statement: This allows us to use multiple if…else statments.


We use this when there are multiple conditions of TRUE cases.
Syntax:
if (condition) {
// if TRUE then execute this code
}
elseif {
// if TRUE then execute this code
}
elseif {
// if TRUE then execute this code
}
else {
// if FALSE then execute this code
}
Example:
<?php

$x = "August";

if ($x == "January") {

echo "Happy Republic Day";

elseif ($x == "August") {

echo "Happy Independence Day!!!";

else{

echo "Nothing to show";

?>

Output:
Happy Independence Day!!!
Flowchart:

4. Switch Statement: The “switch” performs in various cases i.e., it has


various cases to which it matches the condition and appropriately executesa
particular case block. It first evaluates an expression and then compares with
the values of each case. If a case matches then the same case is executed. To
use switch, we need to get familiar with two different keywords
namely, break and default.
o The break statement is used to stop the automatic control flow into
the next cases and exit from the switch case.
o The default statement contains the code that would execute if none
of the cases match.
Syntax:
switch(n) {
case statement1:
code to be executed if n==statement1;
break;
case statement2:
code to be executed if n==statement2;
break;
case statement3:
code to be executed if n==statement3;
break;
case statement4:
code to be executed if n==statement4;
break;
......
default:
code to be executed if n != any case;

Flowchart:
Ternary Operators
In addition to all this conditional statements, PHP provides a shorthand way of
writing if…else, called Ternary Operators. The statement uses a question mark (?)
and a colon (:) and takes three operands: a condition to check, a result for TRUE
and a result for FALSE.
Syntax:
(condition) ? if TRUE execute this : otherwise execute this;
Example:
<?php $x = -12;

echo ($x > 0) ? 'The number is positive' :

'The number is negative'; ?>

Output:
The number is negative

PHP Functions
PHP function is a piece of code that can be reused many
times. It can take input as argument list and return value.
There are thousands of built-in functions in PHP.
PHP User-defined Functions
We can declare and call user-defined functions easily. Let's see the
syntax to declare user-defined functions.
Syntax
function functionname()
{
//code to be executed
}
PHP Functions Example
<?php

function sayHello()
{
echo "Hello PHP Function";
}

sayHello();//calling function
?>

PHP Function Arguments

We can pass the information in PHP function through


arguments which is separated by comma.
PHP supports Call by Value (default), Call by
Reference, Default argument values and Variable-length
argument list.

PHP function Call by Value (default)


<?php
function sayHello($name,$age){
echo "Hello $name, you are $age years old<br/>";
}
sayHello("Aman",37);
sayHello("Veer",69);
sayHello("Prem",33);
?>
PHP function Call By Reference
By default, value passed to the function is call by value. To pass
value as a reference, you need to use ampersand (&) symbol before
the argument name.
<?php
function adder(&$str2)
{
$str2 .= 'its Call By Reference';
}
$str = 'Good Morning students';
adder($str);
echo $str;
?>
Output:

Good Morning students its Call By Reference

PHP function Setting Default Values for Function parameter


o PHP allows us to set default argument values for function parameters.
o If we do not pass any argument for a parameter with default value
then PHP will use the default set value for this parameter in the
function call.
o Example:
<?php

// function with default parameter

function detail($str, $num=12)

echo "$str is $num years old \n";

// Caling the function


defGeek("Ram", 15);

// In this call, the default value 12

// will be considered

defGeek("Adam");

?>

Output:
Ram is 15 years old
Adam is 12 years old
In the above example, the parameter $num has a default value 12, if we do not pass
any value for this parameter in a function call then this default value 12 will be
considered. Also the parameter $str has no default value , so it is compulsory.

PHP functions to accepts any number of arguments


 Parameterized Function:
o The information or variable, within the function’s parenthesis, are
called parameters. These are used to hold the values executableduring
runtime. A user is free to take in as many parameters as he wants,
separated with a comma(,) operator.
o These parameters are used to accept inputs during runtime. While
passing the values like during a function call, they are called
o
o arguments. An argument is a value passed to a function and a
parameter is used to hold those arguments.
o In common term, both parameter and argument mean the same. We
need to keep in mind that for every parameter, we need to pass its
corresponding argument.
o Syntax:
Example:
<?p

function function_name($first_parameter, $second_parameter)


{ executable code;
}
// function along with three parameters

function pro($num1, $num2, $num3)

$product = $num1 * $num2 * $num3;

echo "The product is $product";

// Calling the function

// Passing three arguments

pro(2, 3, 5);

?>

Output:
The product is 30

 Returning Values from Functions


o Functions can also return values to the part of program from where it
is called.
o The return keyword is used to return value back to the part of
program, from where it was called. The returning value may be of any
type including the arrays and objects.
o The return statement also marks the end of the function and stops the
execution after that and returns the value.
o Example:
<?php

// function along with three parameters

function pro($num1, $num2, $num3)

$product = $num1 * $num2 * $num3;

return $product; //returning the product

}
// storing the returned value

$retValue = pro(2, 3, 5);

echo "The product is $retValue";

?>

Output:
The product is 30

 Parameter passing to Functions


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

// pass by value

function val($num) {

$num += 2;

return $num;

// pass by reference

function ref(&$num) {

$num += 10;

return $num;
}

$n = 10;

val($n);

echo "The original value is still $n \n";

ref($n);

echo "The original value changes to $n";

?>

Output:
The original value is still 10
The original value changes to 20

Explain in details predefined functions


PHP provides us with huge collection of built-in library functions. These functions
are already coded and stored in form of functions. To use those we just need to call
them as per our requirement like, var_dump, fopen(), print_r(), gettype() and so on.

Explain various date and time formats.


 The PHP date() function converts a timestamp to a more readable date and
time format.
 The computer stores dates and times in a format called UNIX Timestamp,
which measures time as number of seconds since the beginning of the Unix
epoch (midnight Greenwich Mean Time on January 1, 1970 i.e. January 1,
1970 00:00:00 GMT ).
 Since this is an impractical format for humans to read, PHP converts a
timestamp to a format that is readable and more understandable to humans.
 Syntax:
date(format, timestamp)
 Explanation:
o The format parameter in the date() function specifies the format of
returned date and time.
o Timestamp is an optional parameter, if it is not included then current
date and time will be used.
o Below program explains usage of date() function in PHP

<?php
echo "Today's date is :";
$today = date("d/m/Y");
echo $today;
?>
Output:
Today's date is :05/12/2017

 Formatting options available in date() function: The format parameter of


the date() function is a string that can contain multiple characters allowing to
generate dates in various formats.
Date-related formatting characters that are commonly used in format string:
o d – Represents day of the month; two digits with leading zeros (01 or
31).
o D – Represents day of the week in text as an abbreviation (Mon to
Sun).
o m – Represents month in numbers with leading zeros (01 or 12).
o M – Represents month in text, abbreviated (Jan to Dec).
o y – Represents year in two digits (08 or14).
o Y – Represents year in four digits (2008 or 2014).
o The parts of the date can be separated by inserting other characters,
like hyphens (-), dots (.), slashes (/), or spaces to add additional visual
formatting.
Get a Time

Here are some characters that are commonly used for times:

 H - 24-hour format of an hour (00 to 23)


 h - 12-hour format of an hour with leading zeros (01 to 12)
 i - Minutes with leading zeros (00 to 59)
 s - Seconds with leading zeros (00 to 59)
 a - Lowercase Ante meridiem and Post meridiem (am or pm)
ex:
<?php
echo "Today's date in various formats:" ;
echo date("d/m/Y") ;
echo date("d-m-Y") ;
echo date("d.m.Y") ;
echo date("d.M.Y/l");
?>

The example below outputs the current time in the specified format:
<?php
echo "The time is " . date("h:i:sa");
?>

Note that the PHP date() function will return the current
date/time of the server!

Note:
If the time you got back from the code is not correct, it's probably because your server is in another
country or set up for a different timezone.

So, if you need the time to be correct according to a specific location, you can set the timezone you
want to use.

The example below sets the timezone to "America/New_York", then outputs the current time in the
specified format:

<?php
date_default_timezone_set("America/New_York");
echo "The time is " . date("h:i:sa");
?>

PHP mktime() Function


 The mktime() function is used to create the timestamp for a specific date
and time.The PHP mktime() function returns the Unix
timestamp for a date. If no date and time is provided, the timestamp
for the current date and time is returned.
 Syntax:
mktime(hour, minute, second, month, day, year)
 Input:
<?php
echo mktime(23, 21, 50, 11, 25, 2017);
?>
 Output:
1511652110
 The above code creates a time stamp for 25th Nov 2017 ,23 hrs 21mins
50secs.
o <?php
$d=mktime(11, 14, 54, 8, 12, 2014);
echo "Created date is " . date("Y-m-d
h:i:sa", $d);
?>

Explain various Math function available in PHP.


Some examples of mathematical functions in PHP are as follows:
1. abs() :
This function takes negative value as input and returns the absolute (positive) value
of a integer or float number.
Syntax :
abs(number);
In this function ‘number’ can be float or integer.

Example:
<?php
// PHP code to return absolute value.
function absolute($degree)
{
return (abs($degree));
}

// Driver Code
$number = -8.4;
echo(absolute($number));
?>
Output : 8.4

2. pi() :
This function returns the value of pi. The named constant M_PI is identical to pi().
Syntax :
pi();
Example :
<?php
# PHP function to convert degree to radian value.
echo(pi());
?>
Output :
3.1415926535898
3.decbin() :
This function convert a decimal number to binary number.
Syntax :
pi();
Example :
<?php
# PHP function to convert a decimal number to binary number.
echo(decbin(20));
?>
Output : 101
4.exp() :
This function calculate exponential of e

5. floor() :
This function takes numeric value as argument and returns the next lowest integer.
value (as float) by rounding down value if necessary

Syntax :
floor($number);
Example:
<?php
echo(floor(0.60)."\n");
echo(floor(5)."\n");
echo(floor(-5.9));
?>
Output :
0
5
-6
6. ceil() :
This function takes numeric value as argument and returns the next highest integer
value by rounding up value if necessary.
Syntax :
ceil($number);
Example :
<?php
echo(ceil(0.60)."\n");
echo(ceil(-5.9));
?>
Output:

1
-5

7. round() :
This function takes numeric value as argument and returns the next highest integer
value by rounding up value if necessary.
Syntax :

round(number, precision, mode);


In this, number specifies the value to round, precision specifies the number of
decimal digits to round to (Default is 0) and, mode(optional) specifies one of the
following constants to specify the mode in which rounding occurs :

 PHP_ROUND_HALF_UP : (set by Default) Rounds number up to


precision decimal, when it is half way there. Rounds 1.5 to 2 and -1.5 to -2
 PHP_ROUND_HALF_DOWN : Round number down to precision decimal
places, when it is half way there. Rounds 1.5 to 1 and -1.5 to -1
 PHP_ROUND_HALF_EVEN : Round number to precision decimal places
towards the next even value.
 PHP_ROUND_HALF_ODD : Round number to precision decimal places
towards the next odd value.

Example :
<?php
echo(round(1.95583, 2)."\n");
echo(round(1241757, -3)."\n");
echo(round(9.5, 0, PHP_ROUND_HALF_UP)."\n");
echo(round(9.5, 0, PHP_ROUND_HALF_DOWN)."\n");
echo(round(9.5, 0, PHP_ROUND_HALF_EVEN)."\n");
echo round(9.5, 0, PHP_ROUND_HALF_ODD);
?>
Output :
1.96
1242000
10
9
10
9

Differentiate while and do-While statement.


Refer answer of explain loops

Write a PHP script to compute factorial of n using while or for loop


<html>
<head>
<title>FACTORIAL OF A NUMBER</title>
</head>
<body>

<font size=5>FACTORIAL OF A NUMBER</font>


<br/>
<br/>
<form action=factorial.php method="post">
ENTER A NUMBER:<input type="text" name="t1">
<br><br>
<input type="submit" value="FACTORIAL">
<?php
if(isset($_POST["t1"]))
{
$n=$_POST["t1"];
$fact=1;
echo "<br/>
<br/>";
echo "Factorial of $n is: ";

while($n>0)
{
$fact=$fact*$n;
$n--;
}
echo "$fact";
}
?>
</form>
</body>
</html>

Write a PHP script to display Fibonacci of length 10


<?php
$num = 0;
$n1 = 0;
$n2 = 1;
echo "<h3>Fibonacci series for first 10 numbers: </h3>";
echo "\n";
echo $n1.' '.$n2.' ';
while ($num < 8 )
{
$n3 = $n2 + $n1;
echo $n3.' ';
$n1 = $n2;
$n2 = $n3;
$num = $num + 1;
?>
Write a short note on Scope of Variables
Variable scope is known as its boundary within which it can be visible or accessed
from code. In other words, it is the context within which a variable is defined.
There are only two scopes available in PHP namely local and global scopes.

1. Local variables (local scope)


2. Global variables (special global scope)
3. Static variables (local scope)
4. Function parameters (local scope)

When a variable is accessed outside its scope it will cause PHP error Undefined
Variable.

1. Local Scope Variables

A local scope is a restricted boundary of a variable within which code block it is


declared. That block can be a function, class or any conditional span. The variable
within this limited local scope is known as the local variable of that specific code
block.

The following code block shows a PHP function. We have declared a


variable $count inside this function. This variable is said to be a local variable of
this function and it is in the local scope of the function block.

<?php

function calculate_count() {

$count = 5;

//will print 5; the value of local variable

echo $count++;

?>
Local variables will be destroyed once the end of the code block is reached. Hence
the same named variables can be declared within different local scopes.

2. Global Scope Variables

As its name, the global scope provides widespread access to the variable declared
in this scope. Variables in global scope can be accessed from anywhere from
outside a function or class independent of its boundary.

PHP global variables can be defined by using global keyword. If we want to use
global variables inside a function, we have to prefix the global keyword with the
variable. The following code shows a code block to learn how to use the global
keyword with a PHP variable to declared it as a global variable.

<?php

$count = 0;

function calculate_count()

{ global $count;

// will print 0 and increment global variable

echo $count++ . "<br/>";


}

calculate_count();

echo $count;

?>
PHP has a predefined superglobal variable called $GLOBALS. It is an associative
array with the name of the variable as key and value as the array element. We can
use this array variable to add an array of PHP variables in a global scope.

Let us change the above example with the global keyword by using $GLOBALS
superglobal to access the variable in global scope.

<?php

$count = 0;

function calculate_count() {

// will print 0 and increment global variable declared outside function

echo $GLOBALS["count"]++ . "<br/>";

calculate_count();

echo $count;

?>

3. Static Variables (local scope)

A static variable is again a variable with local scope. But the difference with the
regular local variable is that it is not destroyed outside the scope boundary. A
variable can be defined by using the ‘static’ keyword inside a function.

A static variable does not lose its value when the program execution goes past the
scope boundary. But it can be accessed only within that boundary. Let me
demonstrate it using the following example code,
The above counter function has the static variable ‘count’ declared within its local
scope. When the function execution is complete, the static count variable still retains
its value for further computation. Every time the counter function is called, the value
of count is incremented. The count value is initialized only once on the first call.
<?php
function counter()

static $count = 0;

echo $count;

$count++;

?>

1. Function Parameters (Local Scope)

Function parameters (arguments) are local variables defined within the local scope
of the function on which it is used as the argument.

Potrebbero piacerti anche