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

PHP Unit1

The document provides an introduction to PHP, covering what PHP is, its history and uses, features, syntax rules, and examples of using echo and print statements. PHP is an open-source scripting language suited for web development and used to handle dynamic content and databases on websites. The document includes the basic 'Hello World' script and explains how to write and run PHP code.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views

PHP Unit1

The document provides an introduction to PHP, covering what PHP is, its history and uses, features, syntax rules, and examples of using echo and print statements. PHP is an open-source scripting language suited for web development and used to handle dynamic content and databases on websites. The document includes the basic 'Hello World' script and explains how to write and run PHP code.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 28

PHP

Unit1:
Introducing PHP – Basic development Concepts – Creating first PHP Scripts –
Using Variable and Operators – Storing Data in variable – Understanding Data
types – Setting and Checking Variables – Data types – Using Constants –
Manipulating Variables with Operators.

What is PHP
PHP is an open-source, interpreted, and object-oriented scripting language that can be
executed at the server-side. PHP is well suited for web development. Therefore, it is used
to develop web applications (an application that executes on the server and generates
the dynamic page.).

PHP was created by Rasmus Lerdorf in 1994 but appeared in the market in 1995. PHP
7.4.0 is the latest version of PHP, which was released on 28 November. Some important
points need to be noticed about PHP are as followed:

617.1K
8. Modules and PHP Abstract class | Build a CMS using OOP PHP CMS tutorial MVC [2020]

o PHP stands for Hypertext Preprocessor.


o PHP is an interpreted language, i.e., there is no need for compilation.
o PHP is faster than other scripting languages, for example, ASP and JSP.
o PHP is a server-side scripting language, which is used to manage the dynamic
content of the website.
o PHP can be embedded into HTML.
o PHP is an object-oriented language.
o PHP is an open-source scripting language.
o PHP is simple and easy to learn language.
Why use PHP
PHP is a server-side scripting language, which is used to design the dynamic web
applications with MySQL database.

o It handles dynamic content, database as well as session tracking for the website.
o You can create sessions in PHP.
o It can access cookies variable and also set cookies.
o It helps to encrypt the data and apply validation.
o PHP supports several protocols such as HTTP, POP3, SNMP, LDAP, IMAP, and
many more.
o Using PHP language, you can control the user to access some pages of your
website.
o As PHP is easy to install and set up, this is the main reason why PHP is the best
language to learn.
o PHP can handle the forms, such as - collect the data from users using forms, save
it into the database, and return useful information to the user. For example -
Registration form.

PHP Features
PHP is very popular language because of its simplicity and open source. There are some
important features of PHP given below:

Performance:

PHP script is executed much faster than those scripts which are written in other
languages such as JSP and ASP. PHP uses its own memory, so the server workload and
loading time is automatically reduced, which results in faster processing speed and
better performance.
Open Source:

PHP source code and software are freely available on the web. You can develop all the
versions of PHP according to your requirement without paying any cost. All its
components are free to download and use.

Familiarity with syntax:

PHP has easily understandable syntax. Programmers are comfortable coding with it.

Embedded:

PHP code can be easily embedded within HTML tags and script.

Platform Independent:

PHP is available for WINDOWS, MAC, LINUX & UNIX operating system. A PHP
application developed in one OS can be easily executed in other OS also.

Database Support:

PHP supports all the leading databases such as MySQL, SQLite, ODBC, etc.

Error Reporting -

PHP has predefined error reporting constants to generate an error notice or warning at
runtime. E.g., E_ERROR, E_WARNING, E_STRICT, E_PARSE.

Loosely Typed Language:

PHP allows us to use a variable without declaring its datatype. It will be taken
automatically at the time of execution based on the type of data it contains on its value.

Web servers Support:

PHP is compatible with almost all local servers used today like Apache, Netscape,
Microsoft IIS, etc.

Security:

PHP is a secure language to develop the website. It consists of multiple layers of security
to prevent threads and malicious attacks.
Control:

Different programming languages require long script or code, whereas PHP can do the
same work in a few lines of code. It has maximum control over the websites like you can
make changes easily whenever you want.

A Helpful PHP Community:

It has a large community of developers who regularly updates documentation, tutorials,


online help, and FAQs. Learning PHP from the communities is one of the significant
benefits.

Web Development
PHP is widely used in web development nowadays. PHP can develop dynamic websites
easily. But you must have the basic the knowledge of following technologies for web
development as well.

o HTML
o CSS
o JavaScript
o Ajax
o XML and JSON
o jQuery

Prerequisite
Before learning PHP, you must have the basic knowledge of HTML,
CSS, and JavaScript. So, learn these technologies for better implementation of PHP.

HTML - HTML is used to design static webpage.

CSS - CSS helps to make the webpage content more effective and attractive.

JavaScript - JavaScript is used to design an interactive website.


First PHP Example
To learn what is the syntax to write basic PHP code, how we can
integrate PHP code in an HTML file and how to run the PHP script and
check the output in the browser.

Hello World script in PHP

All the php code is written inside php code tags which is <?php and ?>.
And the file with php code is saved with an extension .php. Here is a
simple example:

<?php

// code statements

?>

Hence a simple Hello, World! program in PHP will be:

<?php

echo "Hello, World!";

?>

output

Hello, World!

echo is a command used in PHP to display anything on screen.

To include this php code in an HTML document, can do so like this:


<!DOCTYPE>

<html>

<body>

<?php

echo "<h1>Hello, World!</h1>";

?>

</body>

</html

save the file with the name hello_world.php


PHP Syntax Rules

Below we have a listed down the main syntax rules that you must
follow while writing php code.

1. All the php code in a php script should be enclosed within <?
php and ?>, else it will not be considered as php code. Adding
php code inside the PHP tags is known as Escaping to php.

<?php ... ?>


Copy
Apart from the standard <?php and ?>, you can also use
the Short-open tags:

<? ... ?>

Or use the HTML script tags, like we do for adding javascript


code in HTML document:

<script language="PHP"> ... </script>

2. Every expression in PHP ends with a semicolon ;

3. Commenting PHP code: Both single line and multi-line


comments are supported in PHP. For single line comment, we
can either use # or // before the comment line. For example,
4. <?php

5. # This is also a single line comment

6. # another line of comment

7.

8. // This is a single line comment

9. echo "Example for Single line Comments";

?>

And for multi-line comments, we use /* ... */. For example,


<?php

/*

This is also a single line comment

another line of comment

*/

echo "Example for Multi-line Comments";

?>

10. PHP is case sensitive, which means that a variable $tiger is


not same as $Tiger. Both of these, represent two different
variables here.

But all the predefined keywords and functions like if, else, echo etc
are case insensitive.

<?php

echo "Hello, World!";

ECHO "Hello, World!";

?>

Hello, World!

Hello, World!

11. PHP uses curly braces to define a code block.


12.<?php
13. if($zero == 0)

14. {

15. echo "If condition satisfied";

16. echo "This is a code block";

17. }

?>

PHP Echo
PHP echo is a language construct, not a function. Therefore, you don't need to use
parenthesis with it. But if you want to use more than one parameter, it is required to use
parenthesis.

The syntax of PHP echo is given below:

1. void echo ( string $arg1 [, string $... ] )

PHP echo statement can be used to print the string, multi-line strings, escaping
characters, variable, array, etc. Some important points that you must know about the
echo statement are:

o echo is a statement, which is used to display the output.


o echo can be used with or without parentheses: echo(), and echo.
o echo does not return any value.
o We can pass multiple strings separated by a comma (,) in echo.
o echo is faster than the print statement.

PHP echo: printing string


File: echo1.php

20.1M

409

History of Java

Next

Stay

1. <?php
2. echo "Hello by PHP echo";
3. ?>

Output:

Hello by PHP echo

PHP echo: printing multi line string


File: echo2.php

1. <?php
2. echo "Hello by PHP echo
3. this is multi line
4. text printed by
5. PHP echo statement
6. ";
7. ?>

Output:

Hello by PHP echo this is multi line text printed by PHP echo statement

PHP echo: printing escaping characters


File: echo3.php

1. <?php
2. echo "Hello escape \"sequence\" characters";
3. ?>

Output:

Hello escape "sequence" characters

PHP echo: printing variable value


File: echo4.php

1. <?php
2. $msg="Hello JavaTpoint PHP";
3. echo "Message is: $msg";
4. ?>

Output:

Message is: Hello JavaTpoint PHP

PHP Print
Like PHP echo, PHP print is a language construct, so you don't need to use parenthesis
with the argument list. Print statement can be used with or without parentheses: print
and print(). Unlike echo, it always returns 1.

The syntax of PHP print is given below:

1. int print(string $arg)

PHP print statement can be used to print the string, multi-line strings, escaping
characters, variable, array, etc. Some important points that you must know about the
echo statement are:

o print is a statement, used as an alternative to echo at many times to display the output.
o print can be used with or without parentheses.
o print always returns an integer value, which is 1.
o Using print, we cannot pass multiple arguments.
o print is slower than the echo statement.

PHP print: printing string


File: print1.php

30.4M

681

Exception Handling in Java - Javatpoint

1. <?php
2. print "Hello by PHP print ";
3. print ("Hello by PHP print()");
4. ?>

Output:

Hello by PHP print Hello by PHP print()

PHP print: printing multi line string


File: print2.php

1. <?php
2. print "Hello by PHP print
3. this is multi line
4. text printed by
5. PHP print statement
6. ";
7. ?>
Output:

Hello by PHP print this is multi line text printed by PHP print statement

PHP print: printing escaping characters


File: print3.php

1. <?php
2. print "Hello escape \"sequence\" characters by PHP print";
3. ?>

Output:

Hello escape "sequence" characters by PHP print

PHP print: printing variable value


File: print4.php

1. <?php
2. $msg="Hello print() in PHP";
3. print "Message is: $msg";
4. ?>

Output:

Message is: Hello print() in PHP


PHP Data Types, Variables, Constant,
Operators
PHP Data Types

 PHP Variable
 Use of variables
 Variable type casting
 PHP Constant
 PHP Operators
 Arithmetic operators
 Assignment Operators
 Comparison operators
 Logical operators

PHP Data Types


A Data type is the classification of data into a category according to its
attributes;

 Alphanumeric characters are classified as strings


 Whole numbers are classified integers
 Numbers with decimal points are classified as floating points.
 True or false values are classified as Boolean.

PHP is a loosely typed language; it does not have explicit defined data types.
PHP determines the data types by analyzing the attributes of data supplied.
PHP implicitly supports the following data types

 Integer – whole numbers e.g. -3, 0, 69. The maximum value of an


integer is platform-dependent. On a 32 bit machine, it’s usually around 2
billion. 64 bit machines usually have larger values. The constant
PHP_INT_MAX is used to determine the maximum value.
<?php
echo PHP_INT_MAX;
?>
Output:
9223372036854775807

 Floating point number – decimal numbers e.g. 3.14. they are also
known as double or real numbers. The maximum value of a float is
platform-dependent. Floating point numbers are larger than integers.
 Character string – e.g. Hello World
 Boolean – e.g. True or false.

Before we go into more details discussing PHP data types, let’s first discuss
variables.

PHP Variable
A variable is a name given to a memory location that stores data at runtime.

PHP – Variables
Scope can be defined as the range of availability a variable has to the program in which it is
declared. PHP variables can be one of four scope types:
 Local variables

 Function parameters

 Global variables

 Static variables

PHP Local Variables


A variable declared in a function is considered local; that is, it can be referenced solely in
that function. Any assignment outside of that function will be considered to be an entirely
different variable from the one contained in the function:
<?
$x = 4;
function assignx ()
{
$x = 0;
print "\$x inside function is $x. ";
}

assignx();
print "\$x outside of function is $x. ";
?>
This will produce the following result.
$x inside function is 0.
$x outside of function is 4.

PHP Function Parameters


PHP Functions are covered in detail in PHP Function Chapter. In short, a function is a small
unit of program which can take some input in the form of parameters and does some
processing and may return a value.
Function parameters are declared after the function name and inside parentheses. They are
declared much like a typical variable would be:
<?
// multiply a value by 10 and return it to the caller
function multiply ($value) {
$value = $value * 10;
return $value;
}
$retval = multiply (10);
Print "Return value is $retval\n";
?>
This will produce the following result.
Return value is 100

PHP Global Variables


In contrast to local variables, a global variable can be accessed in any part of the program.
However, in order to be modified, a global variable must be explicitly declared to be global
in the function in which it is to be modified. This is accomplished, conveniently enough, by
placing the keyword GLOBAL in front of the variable that should be recognized as global.
Placing this keyword in front of an already existing variable tells PHP to use the variable
having that name. Consider an example:
<?
$somevar = 15;
function addit() {
GLOBAL $somevar;
$somevar++;
print "Somevar is $somevar";
}
addit();
?>
This will produce the following result.
Somevar is 16
PHP Static Variables
The final type of variable scoping that I discuss is known as static. In contrast to the
variables declared as function parameters, which are destroyed on the function's exit, a
static variable will not lose its value when the function exits and will still hold that value
should the function be called again.
You can declare a variable to be static simply by placing the keyword STATIC in front of the
variable name.
<?
function keep_track() {
STATIC $count = 0;
$count++;
print $count;
print " "; PHP

The scope of a variable determines its visibility.

A Php global variable is accessible to all the scripts in an application.


A local variable is only accessible to the script that it was defined in.

Think of a variable as a glass containing water. You can add water into the
glass, drink all of it, refill it again etc.

The same applies for variables.

Variables are used to store data and provide stored data when needed. Just
like in other programming languages, PHP supports variables too. Let’s now
look at the rules followed when creating variables in PHP.

 All variable names must start with the dollar sign e.g.

 Variable names are case sensitive; this means $my_var is different from
$MY_VAR

 All variables names must start with a letter follow other characters e.g.
$my_var1. $1my_var is not a legal variable name.

 Variable names must not contain any spaces, “$first name” is not a legal
variable name. You can instead use an underscore in place of the
space e.g. $first_name. You cant use characters such as the dollar or
minus sign to separate variable names.

Let’s now look at how PHP determines the data type depending on the
attributes of the supplied data.
<?php
$my_var = 1;
echo $my_var;
?>
Output:
1
Floating point numbers
<?php
$my_var = 3.14;
echo $my_var;
?>
Output:
3.14
Character strings
<?php
$my_var ="Hypertext Pre Processor";
echo $my_var;
?>
Output:
Hypertext Pre Processor

PHP $ and $$ Variables


The $var (single dollar) is a normal variable with the name var that stores any value like string, integer, float, etc.

The $$var (double dollar) is a reference variable that stores the value of the $variable inside it.

To understand the difference better, let's see some examples.

Example 1

<?php
$x = "abc";
$$x = 200;
echo $x."<br/>";
echo $$x."<br/>";
echo $abc;
?>

Output:

Example2

1. <?php
2. $x="U.P";
3. $$x="Lucknow";
4. echo $x. "<br>";
5. echo $$x. "<br>";
6. echo "Capital of $x is " . $$x;
7. ?>

Output:
xample3

1. <?php
2. $name="Cat";
3. ${$name}="Dog";
4. ${${$name}}="Monkey";
5. echo $name. "<br>";
6. echo ${$name}. "<br>";
7. echo $Cat. "<br>";
8. echo ${${$name}}. "<br>";
9. echo $Dog. "<br>";
10. ?>

Output:

In the above example, we have assigned a value to the variable name Cat. Value of reference variable ${$name} is assigned
as Dog and ${${$name}} as Monkey.

Now we have printed the values as $name, ${$name}, $Cat, ${${$name}} and $Dog.

Use of Variables
Variables help separate data from the program algorithms.

The same algorithm can be used for different input data values.
For example, suppose that you are developing a calculator program that adds
up two numbers, you can create two variables that accept the numbers then
you use the variables names in the expression that does the addition.

Variable Type Casting


Performing arithmetic computations using variables in a language such
as C# requires the variables to be of the same data type.

Type casting is converting a variable or value into a desired data type.

This is very useful when performing arithmetic computations that require


variables to be of the same data type.

Type casting in PHP is done by the interpreter.

In other languages such as C#, you have to cast the variables. The code
below shows type casting in C#.

The diagram below shows PHP implementing the above example.


PHP also allows you to cast the data type.
This is known as explicit casting. The code below demonstrates explicit type
casting.
<?php
$a = 1;
$b = 1.5;
$c = $a + $b;
$c = $a + (int) $b;
echo $c;
?>
Output:
2
Above Code Output 2 The var_dump function is used to determine the data
type. The code below demonstrates how to use the var_dump function.
<?php
$a = 1;
var_dump($a);
$b = 1.5;
var_dump($b);
$c = "I Love PHP";
var_dump($c);
$d = true;
var_dump($d);
?>
Output:
int(1) float(1.5) string(10) "I Love PHP" bool(true)

PHP Constant
Define constant– A constant is a variable whose value cannot be changed at
runtime.

Suppose we are developing a program that uses the value of PI 3.14, we can
use a constant to store its value.

Let’s now look at an example that defines a constant. define(‘PI’,3.14);


//creates a constant with a value of 3.14 Once you define PI as 3.14 , writing a
code like below will generate an error PI = 4; //PI has been defined as a
constant therefore assigning a value is not permissible.

PHP Operators
Arithmetic operators
Arithmetic operators are used to perform arithmetic operations on numeric
data. The concatenate operator works on strings values too. PHP supports
the following operators.

Operator Name Description Example


+ Addition Summation of x and y 1 + 1; 2
– Subtraction Difference between x and y 1 – 1; 0
* Multiplication Multiplies x and y 3 * 7; 21
/ Division Quotient of x and y 45 / 5; 9
% PHP Modulus Gives remainder of dividing x and y 10 % 3; 1
-n Negation Turns n into a negative number -(-5); 5
x.y Concatenation Puts together x and y “PHP” . ” ROCKS”;10 . 3; PH
Assignment Operators
Assignment operators are used to assign values to variables. They can also
be used together with arithmetic operators.

Operator Name Description Example Output


x=? assignment Assigns the value of x to ? $x = 5; 5
x += ? addition Increments the value of x by ? $x = 2;$x += 1; 3
X -= ? subtraction Subtracts ? from the value of x $x = 3;$x -= 2; 1
X *=? multiplication Multiplies the value of x ? times $x = 0;$x *=9; 0
X /=? division Quotient of x and ? $x = 6;$x /=3; 2
X %=? modulus The reminder of dividing x by? $x = 3;$x %= 2; 1
X .=? concatenate Puts together items ” $x = ‘Pretty’;$x .= ‘ Cool!’;” Pretty Cool!
Comparison operators
Comparison operators are used to compare values and data types.

Operator Name Description Example Output


X == y Equal Compares x and y then returns true if they are equal 1 == “1”; True or 1
1 === False or 0. Since 1 is
X === y identical Compares both values and data types.
“1”; integer and “1” is string
X != y, x <> Compares values of x and y. returns true if the
PHP Not equal 2 != 1; True or 1
y values are not equal
Compares values of x and y. returns true if x is
X>y Greater than 3 > 1; True or 1
greater than y
Compares values of x and y. returns true if x is less
X<y Less than 2 < 1; False or 0
than y
Greater than or Compares values of x and y. returns true if x is
X >= y 1 >=1 True or 1
equal greater than or equal to y
Operator Name Description Example Output
Less than or Compares values of x and y. returns true if x is
X <= y 8 <= 6 False or 0
equal greater than or equal to y
Logical operators
When working with logical operators, any number greater than or less than
zero (0) evaluates to true. Zero (0) evaluates to false.

Operator Name Description Example Output


X and y, x && y And Returns true if both x and y are equal 1 and 4;True&& False; True or 1False or 0
X or y, x || y Or Returns true if either x or y is true 6 or 9;0 || 0; True or 1False or 0
X xor y Exclusive or, xor Returns true if only x is true or only y is true 1 xor 1;1 xor 0; False or 0True or 1
!x Not Returns true if x is false and false if x is true !0; True or 1

PHP Comments
PHP comments can be used to describe any line of code so that other developer can
understand the code easily. It can also be used to hide any code.

PHP supports single line and multi line comments. These comments are similar to C/C+
+ and Perl style (Unix shell style) comments.

PHP Single Line Comments


There are two ways to use single line comments in PHP.

o // (C++ style single line comment)


o # (Unix Shell style single line comment)

1. <?php
2. // this is C++ style single line comment
3. # this is Unix Shell style single line comment
4. echo "Welcome to PHP single line comments";
5. ?>

Output:
30.5M
529
Hello Java Program for Beginners

Welcome to PHP single line comments

PHP Multi Line Comments


In PHP, we can comments multiple lines also. To do so, we need to enclose all lines
within /* */. Let's see a simple example of PHP multiple line comment.

1. <?php
2. /*
3. Anything placed
4. within comment
5. will not be displayed
6. on the browser;
7. */
8. echo "Welcome to PHP multi line comment";
9. ?>

Output:

Welcome to PHP multi line comment

Summary
 PHP is a loosely typed language.
 Variables are memory locations used to store data
 The value of constants cannot be changed at runtime
 Type casting is used to convert a value or variable into a desired data
type
 Arithmetic operators are used to manipulate numeric data
 Assignment operators are used to assign data to variables
 Comparison operators are used to compare variables or values
 Logical operators are used to compare conditions or values

You might also like