Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

php1 2

Uploaded by

suryanarayansu07
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

php1 2

Uploaded by

suryanarayansu07
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

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.

Below, we have an example of a simple PHP file, with a PHP script that uses a built-in PHP
function "echo" to output the text "Hello World!" on a web page:

Example

<!DOCTYPE html>
<html>
<body>

<h1>My first PHP page</h1>

<?php
echo "Hello World!";
?>

</body>
</html>
PHP statements end with a semicolon (;)

 Variables:
 Variable in any programming language is a name given to a memory location that
holds a value.
 You can say that variables are containers for any type of values.
 There are some rules to write variable names in PHP.
 Rules for variable names:
o Variable names in PHP start with a dollar ($) sign followed by the variable
name.
o Variable name can contain alphanumeric characters and underscore (_).
o Variable names must start with a letter or an underscore (_). (For eg: $abc,
$x1, $_g, $abc_1 etc.)
o Variable names cannot start with a number.
o Variable names are case-sensitive. (for eg: $x and $X are treated as two
different variables.)
 In PHP we don’t use any command to declare variables.
 A variable is created as soon as you assign a value to it.
 A variable takes a datatype according to the value assigned to it.
 Since we don’t have to specify datatypes for PHP variables, PHP is called as
loosely typed language.
 Scope of variables:

o Variables can be declared anywhere in the program.


o Scope of a variable is a part of the program where the variable is
accessible.
o PHP has three different variable scopes:

o Local
o Global
o static

o Local scope:

o A variable declared within a function has a local scope and can be


accessed within a function only.
o A function is a small program performing a particular task which is
called when required.

o Global scope:
o A variable declared outside a function has a global scope and can
be accessed outside the function only.
o Actually global variables can be accessed anywhere using the
global keyword.
o Static scope:

o A variable declared with static keyword is said to have static scope


within the function.
o Normally when variables are executed, they lose their values or
memory.
o But when a variable is declared as static, it doesn’t lose its value. It
remains static within multiple function calls.

 Variable declaration:

o Variable is declared as follows:

$variable_name=value;

o Example of variable declaration is given below:

$x=5;

o $x is a variable and 5 is a value assigned to $x variable using assignment


operator (=). The assignment operator assigns the right hand side value to
the left hand side variable in an expression.
o The variable name can be just alphabets or they can be some descriptive
names like $school_name, $names, $games etc.

 In PHP we can print a value of variable using an echo statement as follows:

<?php

$x=10;
echo $x;

?>

 Output of this is shown below:

fig 1

 Constants:

 Constants are the variables whose values are not changed throughout the script.
 A valid constant variable do not have a $ sign before its name.
 It starts with a letter or an underscore (_).
 Constants have global scope in the whole script.
 Constants are useful in situations where same value is used in many places. For
example: if we want to calculate an area and perimeter of a circle, we require the
value of PI in both the cases. So we can have the value of PI defined as a constant
and can use it effectively.
 If we want to create an array of names having length 10, we can define the length
10 as a constant which will be used anywhere required. But if for some reason we
decided to increase the length to 20, we can just change the value 10 to 20 in the
constant definition which will be replicated everywhere.
 Constants are declared using inbuilt define() function.
 It takes 3 parameters,

o Name of the constant


o Value of the constant
o Whether the constant should be case-insensitive. Default value is false.

 The third parameter of define() function is optional.


 The false value of third parameter of define() function denotes that the constant
name is case-sensitive and true value indicates that the constant name is case-
insensitive.
 Let us see how it is used in a program.
 First we will see the case-sensitive constant.

o Write the following code in index.php file:

<?php

define("MESSAGE","Welcome to PHP!");

echo MESSAGE;

?>

o Here, the third parameter is not given. By default it takes false value that
means the constant becomes case sensitive.
o In the above code for defining constant we have used define() function.
Name of the constant is MESSAGE and value is Welcome to PHP!.
The value of constant is printed using echo statement.

o If we use the constant name as message i.e. in small case as shown


below:

<?php

define("MESSAGE","Welcome to PHP!");

echo message;

?>

o It will give error as our constant is case sensitive. Echo statement should
have message in upper case letters.

 Constants can have any type of value.


 Let us now see an example of case-insensitive constant.

o Write the following code to define another constant:

<?php

define("PI",3.14,true);

echo PI;

echo “<br>”;

echo pi;

?>
Here, a constant PI is defined with value 3.14 and third parameter is given as true to
make the constant case-insensitive that means it doesn’t matter whether it is written
in uppercase or lowercase.

The PHP echo Statement

The echo statement can be used with or without parentheses: echo or echo().

Display Text

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

<?php
echo "<h2>PHP is Fun!</h2>";
echo "Hello world!<br>";
echo "I'm about to learn PHP!<br>";
echo "This ", "string ", "was ", "made ", "with multiple parameters.";
?>

Display Variables

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

Example

<?php
$txt1 = "Learn PHP";
$txt2 = "nc college";
$x = 5;
$y = 4;

echo "<h2>" . $txt1 . "</h2>";


echo "Study PHP at " . $txt2 . "<br>";
echo $x + $y;
?>
The PHP print Statement

The print statement can be used with or without parentheses: print or print().

Display Text

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

Example

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

Display Variables

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

Example

<?php
$txt1 = "Learn PHP";
$txt2 = "nc college";
$x = 5;
$y = 4;

print "<h2>" . $txt1 . "</h2>";


print "Study PHP at " . $txt2 . "<br>";
print $x + $y;
?>

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;
?>
PHP Integer

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

Rules for integers:

 An integer must have at least one digit


 An integer must not have a decimal point
 An integer can be either positive or negative
 Integers can be specified in: decimal (base 10), hexadecimal (base 16), octal (base
8), or binary (base 2) notation

In the following example $x is an integer. The PHP var_dump() function returns the data type
and value:

Example

<?php
$x = 5985;
var_dump($x);
?>

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);
?>

PHP Boolean

A Boolean represents two possible states: TRUE or FALSE.

$x = true;
$y = false;

Booleans are often used in conditional testing. You will learn more about conditional testing in
a later chapter of this tutorial.
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);
?>

PHP Object

Classes and objects are the two main aspects of object-oriented programming.

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

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

Let's assume we have a class named Car. A Car can have properties like model, color, etc.
We can define variables like $model, $color, and so on, to hold the values of these properties.

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

If you create a __construct() function, PHP will automatically call this function when you
create an object from a class.

Example

<?php
class Car {
public $color;
public $model;
public function __construct($color, $model) {
$this->color = $color;
$this->model = $model;
}
public function message() {
return "My car is a " . $this->color . " " . $this->model . "!";
}
}

$myCar = new Car("black", "Volvo");


echo $myCar -> message();
echo "<br>";
$myCar = new Car("red", "Toyota");
echo $myCar -> message();
?>

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);
?>

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.

PHP provides us with many operators to perform such operations on various operands or
variables, or values. These operators are nothing but symbols needed to perform
operations of various types. Given below are the various groups of operators:
 Arithmetic Operators
 Logical or Relational Operators
 Comparison Operators
 Conditional or Ternary Operators
 Assignment Operators
 Spaceship Operators (Introduced in PHP 7)
 Array Operators
 Increment/Decrement Operators
 String Operators
Let us now learn about each of these operators in detail.
Arithmetic Operators:
The arithmetic operators are used to perform simple mathematical operations like addition,
subtraction, multiplication, etc. Below is the list of arithmetic operators along with their
syntax and operations in PHP.

Operato Name Syntax Operation


r

+ Addition $x + $y Sum the operands

– Subtraction $x – $y Differences the operands


Operato Name Syntax Operation
r

* Multiplication $x * $y Product of the operands

/ Division $x / $y The quotient of the operands

** Exponentiation $x ** $y $x raised to the power $y

% Modulus $x % $y The remainder of the operands

Note: The exponentiation has been introduced in PHP 5.6.


Example: This example explains the arithmetic operator in PHP.

 PHP

<?php
$x = 29; // Variable 1
$y = 4; // Variable 2

// Some arithmetic operations


on
// these two variables
echo ($x + $y), "\n";
echo($x - $y), "\n";
echo($x * $y), "\n";
echo($x / $y), "\n";
echo($x % $y), "\n";
?>
Output:
33
25
116
7.25
1
Logical or Relational Operators:
These are basically used to operate with conditional statements and expressions.
Conditional statements are based on conditions. Also, a condition can either be met or
cannot be met so the result of a conditional statement can either be true or false. Here are
the logical operators along with their syntax and operations in PHP.

Operator Name Syntax Operation

Logical $x and
and True if both the operands are true else false
AND $y

or Logical OR $x or $y True if either of the operands is true else false

Logical True if either of the operands is true and false if both


xor $x xor $y
XOR are true
Operator Name Syntax Operation

Logical
&& $x && $y True if both the operands are true else false
AND

|| Logical OR $x || $y True if either of the operands is true else false

Logical
! !$x True if $x is false
NOT
Example: This example describes the logical & relational operator in PHP.

 PHP

<?php
$x = 50;
$y = 30;
if ($x == 50 and $y ==
30)
echo "and Success \n";

if ($x == 50 or $y == 20)
echo "or Success \n";

if ($x == 50 xor $y ==
20)
echo "xor Success \n";

if ($x == 50 && $y == 30)


echo "&& Success \n";

if ($x == 50 || $y == 20)
echo "|| Success \n";

if (!$z)
echo "! Success \n";
?>
Output:
and Success
or Success
xor Success
&& Success
|| Success
! Success
Comparison Operators: These operators are used to compare two elements and outputs
the result in boolean form. Here are the comparison operators along with their syntax and
operations in PHP.

Operator Name Syntax Operation

== Equal To $x == $y Returns True if both the operands are equal

!= Not Equal To $x != $y Returns True if both the operands are not equal
Operator Name Syntax Operation

<> Not Equal To $x <> $y Returns True if both the operands are unequal

$x === Returns True if both the operands are equal and


=== Identical
$y are of the same type

Returns True if both the operands are unequal


!== Not Identical $x == $y
and are of different types

< Less Than $x < $y Returns True if $x is less than $y

> Greater Than $x > $y Returns True if $x is greater than $y

Less Than or
<= $x <= $y Returns True if $x is less than or equal to $y
Equal To

Greater Than or
>= $x >= $y Returns True if $x is greater than or equal to $y
Equal To
Example: This example describes the comparison operator in PHP.

 PHP

<?php
$a = 80;
$b = 50;
$c = "80";

// Here var_dump function has been used to


// display structured information. We will learn
// about this function in complete details in further
// articles.
var_dump($a == $c) + "\n";
var_dump($a != $b) + "\n";
var_dump($a <> $b) + "\n";
var_dump($a === $c) + "\n";
var_dump($a !== $c) + "\n";
var_dump($a < $b) + "\n";
var_dump($a > $b) + "\n";
var_dump($a <= $b) + "\n";
var_dump($a >= $b);
?>
Output:
bool(true)
bool(true)
bool(true)
bool(false)
bool(true)
bool(false)
bool(true)
bool(false)
bool(true)
Conditional or Ternary Operators :
These operators are used to compare two values and take either of the results
simultaneously, depending on whether the outcome is TRUE or FALSE. These are also
used as a shorthand notation for if…else statement that we will read in the article on
decision making.
Syntax:
$var = (condition)? value1 : value2;
Here, the condition will either evaluate as true or false. If the condition evaluates to True,
then value1 will be assigned to the variable $var otherwise value2 will be assigned to it.

Operator Name Operation

If the condition is true? then $x : or else $y. This means that if the
?: Ternary condition is true then the left result of the colon is accepted otherwise
the result is on right.

Example: This example describes the Conditional or Ternary operators in PHP.

 PHP

<?php
$x = -12;
echo ($x > 0) ? 'The number is positive' : 'The number is
negative';
?>
Output:
The number is negative
Assignment Operators: These operators are used to assign values to different variables,
with or without mid-operations. Here are the assignment operators along with their syntax
and operations, that PHP provides for the operations.

Operator Name Syntax Operation

Operand on the left obtains the value of the


= Assign $x = $y
operand on the right

+= Add then Assign $x += $y Simple Addition same as $x = $x + $y

-= Subtract then Assign $x -= $y Simple subtraction same as $x = $x – $y

*= Multiply then Assign $x *= $y Simple product same as $x = $x * $y

Divide then Assign


/= $x /= $y Simple division same as $x = $x / $y
(quotient)

Divide then Assign $x %=


%= Simple division same as $x = $x % $y
(remainder) $y

Example: This example describes the assignment operator in PHP.

 PHP

<?php
// Simple assign operator
$y = 75;
echo $y, "\n";

// Add then assign operator


$y = 100;
$y += 200;
echo $y, "\n";

// Subtract then assign operator


$y = 70;
$y -= 10;
echo $y, "\n";

// Multiply then assign operator


$y = 30;
$y *= 20;
echo $y, "\n";

// Divide then assign(quotient) operator


$y = 100;
$y /= 5;
echo $y, "\n";

// Divide then assign(remainder)


operator
$y = 50;
$y %= 5;
echo $y;
?>
Output:
75
300
60
600
20
0
Array Operators: These operators are used in the case of arrays. Here are the array
operators along with their syntax and operations, that PHP provides for the array operation.

Operator Name Syntax Operation

+ Union $x + $y Union of both i.e., $x and $y

== Equality $x == $y Returns true if both has same key-value pair

!= Inequality $x != $y Returns True if both are unequal

$x === Returns True if both have the same key-value pair in the
=== Identity
$y same order and of the same type
Operator Name Syntax Operation

Non- $x !==
!== Returns True if both are not identical to each other
Identity $y

<> Inequality $x <> $y Returns True if both are unequal

Example: This example describes the array operation in PHP.

 PHP

<?php
$x = array("k" => "Car", "l" => "Bike");
$y = array("a" => "Train", "b" =>
"Plane");

var_dump($x + $y);
var_dump($x == $y) + "\n";
var_dump($x != $y) + "\n";
var_dump($x <> $y) + "\n";
var_dump($x === $y) + "\n";
var_dump($x !== $y) + "\n";
?>
Output:
array(4) {
["k"]=>
string(3) "Car"
["l"]=>
string(4) "Bike"
["a"]=>
string(5) "Train"
["b"]=>
string(5) "Plane"
}
bool(false)
bool(true)
bool(true)
bool(false)
bool(true)
Increment/Decrement Operators: These are called the unary operators as they work on
single operands. These are used to increment or decrement values.

Operator Name Syntax Operation

++ Pre-Increment ++$x First increments $x by one, then return $x

— Pre-Decrement –$x First decrements $x by one, then return $x

++ Post-Increment $x++ First returns $x, then increment it by one


Operator Name Syntax Operation

— Post-Decrement $x– First returns $x, then decrement it by one


Example: This example describes the Increment/Decrement operators in PHP.

 PHP

<?php
$x = 2;
echo ++$x, " First increments then prints \
n";
echo $x, "\n";

$x = 2;
echo $x++, " First prints then increments \
n";
echo $x, "\n";

$x = 2;
echo --$x, " First decrements then prints \n";
echo $x, "\n";

$x = 2;
echo $x--, " First prints then decrements \n";
echo $x;
?>
Output:
3 First increments then prints
3
2 First prints then increments
3
1 First decrements then prints
1
2 First prints then decrements
1
String Operators: This operator is used for the concatenation of 2 or more strings using
the concatenation operator (‘.’). We can also use the concatenating assignment operator
(‘.=’) to append the argument on the right side to the argument on the left side.

Operator Name Syntax Operation

. Concatenation $x.$y Concatenated $x and $y

Concatenation and First concatenates then assigns, same as


.= $x.=$y
assignment $x = $x.$y
Example: This example describes the string operator in PHP.

 PHP

<?php
$x = "bca";
$y = "4th";
$z = "sem!!!";
echo $x . $y . $z, "\n";
$x .= $y . $z;
echo $x;
?>
Output:
Spaceship Operators:
PHP 7 has introduced a new kind of operator called spaceship operator. The spaceship
operator or combined comparison operator is denoted by “<=>“. These operators are used
to compare values but instead of returning the boolean results, it returns integer values. If
both the operands are equal, it returns 0. If the right operand is greater, it returns -1. If the
left operand is greater, it returns 1. The following table shows how it works in detail:

Operator Syntax Operation

$x < $y $x <=> $y Identical to -1 (right is greater)

$x > $y $x <=> $y Identical to 1 (left is greater)

$x <= $y $x <=> $y Identical to -1 (right is greater) or identical to 0 (if both are equal)

$x >= $y $x <=> $y Identical to 1 (if left is greater) or identical to 0 (if both are equal)

$x == $y $x <=> $y Identical to 0 (both are equal)

$x != $y $x <=> $y Not Identical to 0


Example: This example illustrates the use of the spaceship operator in PHP.

 PHP

<?php
$x = 50;
$y = 50;
$z = 25;

echo $x <=> $y;


echo "\n";

echo $x <=> $z;


echo "\n";

echo $z <=> $y;


echo "\n";

// We can do the same for


Strings
$x = "Ram";
$y = "Krishna";

echo $x <=> $y;


echo "\n";

echo $x <=> $y;


echo "\n";

echo $y <=> $x;


?>
Output:
0
1
-1
1
1
-1

You might also like