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

PHP

Uploaded by

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

PHP

Uploaded by

Sahitee Basani
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

PHP is a server-side scripting language, which is used to manage dynamic

web pages, databases and build websites with features like session tracking
and e-commerce. On a day of 1995, Rasmus Lerdorf unleashed the first
version of “Hypertext Preprocessor” also known as the PHP language. It is
also integrated with several popular databases like MySQL, PostgreSQL,
Microsoft SQL Server, Oracle etc.

Uses of PHP

PHP can perform several system functions like opening files, CRUD
operations on data stores, general-purpose scripting, etc. Besides system
operations, there are also other uses like

a. Handling Forms: PHP can handle form operations. It can gather data,
save data to a file and send data through emails.
b. Database Operations: PHP can also create, read, update and delete
elements in your database.
c. Encryption: It can perform advanced encryption and encrypt data for you.
d. Dynamic Page Content: It can generate dynamic page content.

Basic Syntax PHP

A PHP script can be written anywhere inside the HTML document. A PHP
script starts with <?php tag and ends with ?>. We can write our logic inside
this tag and it will be executed accordingly.

<?php
// PHP code goes here
?>

Displaying output in php

In php,Output is displayed on the browser using echo as follows:

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

A basic PHP Hello World program looks something like this. We will use a
built-in PHP function “echo” to output the text “Hello World!” on our
webpage.

<!DOCTYPE html>
<html>
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello World!";
?>
</body>
</html>

Variables are containers that can store information which can be


manipulated or referenced later by the programmer within the code.

In PHP, we don’t need to declare the variable type explicitly. The type of
variable is determined by the value it stores. There are some important
things to know about variables in PHP.

 All variables should be denoted with a Dollar Sign ($)


 Variables are assigned with the = operator, with the variable on the left-
hand side and the expression to be evaluated on the right.
 Variable names can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ ).
 Variables must start with a letter or the underscore “_” character.
 Variables are case sensitive
 Variable names cannot start with a number.
For Example:

<?php
$txt = "Hello world!"; # Type String
$x = 5; # Type int
$y = 10.5; # Type Float
?>

Data type specifies the type of value a variable requires to do various


operations without causing an error. By default, PHP provides the following
built-in data types:

 String
 Integer
 Float
 Boolean
 Array
 NULL

1. String

A string is a sequence of characters that holds letters and numbers. It can


be anything written inside single or double quotes.
For Example:

<?php
$x = "Hello world!";
echo $x;
?>
2. Integer

An integer is a non-decimal number typically ranging between -


2,147,483,648 and 2,147,483,647.

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

3. Float

A float is a number with a decimal point. It can be an exponential number or


a fraction.

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

4. Boolean

A Boolean represents two values: True or False.

<?php
$x = true;
$y = false;
?>

5. Array

Array is a collection of similar data elements stored in a single variable.


<?php
$x =array("Rohan", "Lovish", "Harry");
var_dump($x);
?>

6. NULL

Null is a special data type with only one value which is NULL. In PHP, if a
variable is created without passing a value, it will automatically assign itself
a value of NULL.

<?php
$x =null;

1. Arithmetic Operators

Arithmetic operators are used to perform arithmetic operations.


Name Operator Example
Addition + $x+$y
Subtraction - $x-$y
Multiplication * $x*$y
Division / $x/$y
Modulus % $x%$y
Exponentiation ** $x**$y

2. Assignment Operators

These operators are used to assign values to variables.


Name Evaluated as
= a=b
+= a=a+b
-= a=a-b
*= a=a*b
/= a=a/b
%= a=a%b

3. Comparison Operators

These operators are used to compare two values.


Name Operator Example
Equal == $x==$y
Identical === $x===$y
Not equal != $x!=$y
Not equal <> $x<>$y
Not Identical !=== $x!===$y
Greater than > $x>$y
Less than < $x<$y
Greater than or equal to >= $x >= $y
Less than or equal to <= $x <= $y
Spaceship <=> $x <=> $y

4. PHP Increment/ Decrement Operators

These operators are used to increment/ decrement variable’s value.


Name Operator
Pre-Increment ++$x
Post-Increment $x++
Pre-decrement –$x
Post-decrement $x- -

5. PHP Logical Operators

These are the logical operators that combine conditional statements.


Name Operator Example
And and $x and $y
Or or $x or $y
Xor xor $x xor $y
And && $x && $y
Or || $x || $y
Not ! !&x

6. PHP String Operators

PHP has these two operators designed for strings.


Name Operator Example
Concatenation . $text1 . $text2
Concatenation $text1 .=
.=
Assignment $text2

7. PHP Array Operators

These Operators are used to compare arrays.


Name Operator Example
Union + $x + $y
Equality == $x = $y
Identity === $x === $y
Inequality != $x != $y
Inequality <> $x <> $y
!== Non-Identity !== $x !== $y

8. PHP Conditional Operators

These operators assign values to operands based on the outcome of a


certain condition.
Name Operator Example
$x = exp1 ? exp2 :
Ternary ?:
exp3
Null
?? $x = exp1 ?? exp2
Coalescing
PHP Conditional Statements
Conditional Statements are used to perform actions based on different
conditions. Sometimes when we write a program, we want to perform some
different actions for different actions. We can solve this by using conditional
statements.
In PHP we have these conditional statements:

1. if Statement.
2. if-else Statement
3. If-elseif-else Statement
4. Switch statement

1. if Statement

This statement executes the block of code inside the if statement if the
expression is evaluated as True.
Example:

<?php
$x = "22";
if ($x < "20") {
echo "Hello World!";
}
?>

Copy

2. if-else Statement

This statement executes the block of code inside the if statement if the
expression is evaluated as True and executes the block of code inside the
else statement if the expression is evaluated as False.
Example:

<?php
$x = "22";
if ($x < "20") {
echo "Less than 20";
} else {
echo "Greater than 20";
}
?>

Copy

3. If-else-if-else

This statement executes different expressions for more than two conditions.
Example:

<?php
$x = "22";
if ($x == "22") {
echo "correct guess";
} else if ($x < "22") {
echo "Less than 22";
} else {
echo "Greater than 22";
}
?>

Copy
4. Switch Statement

This statement allows us to execute different blocks of code based on


different conditions. Rather than using if-elseif-if, we can use the switch
statement to make our program.
Example:

<?php
$i = "2";
switch ($i) {
case 0:
echo "i equals 0";
break;
case 1:
echo "i equals 1";
break;
case 2:
echo "i equals 2";
break;
default:
echo "i is not equal to 0, 1 or 2";

PHP Iterative Statements


Iterative statements are used to run same block of code over and over again
for a certain number of times.
In PHP, we have the following loops:

1. while Loop
2. do-while Loop
3. for Loop
4. foreach loop
1. While Loop

The While loop in PHP is used when we need to execute a block of code
again and again based on a given condition. If the condition never becomes
false, the while loop keeps getting executed. Such a loop is known as an
infinite loop.
Example:

<?php
$x = 1;
while($x <= 10) {
echo "The number is: $x <br>";
$x++;
}
?>

Copy

2. Do-While Loop

The do-while loop is similar to a while loop except that it is guaranteed to


execute at least once. After executing a part of a program for once, the rest
of the code gets executed based on a given boolean condition.
Example:

<?php
$x =10;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 9);
?>
3. For Loop

The for loop is used to iterate a block of code multiple times.


Example:

<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>

4. Foreach loop
The foreach loop in PHP can be used to access the array indexes in PHP. It
only works on arrays and objects.
Example:

<?php
echo "Welcome to the world of foreach loops <br>";
$arr = array("Bananas", "Apples", "Harpic", "Bread",
"Butter");
foreach ($arr as $value) {
echo "$value <br>";
}
?>
Function Basics
Function arguments are variables of some supported data type that are
processed within the body of the function. It can take input as an argument
and return value.
PHP has more than 1000 built-in functions, and in addition, you can also
create your own functions.

Advantages:

1. Functions reduce the complexity of a program and give it a modular


structure.
2. A function can be defined only once and called many times.
3. It saves a lot of code writing because you don't need to write the same
logic multiple times, you can write the logic once and reuse it.

Built-in Functions: PHP has thousands of built-in functions. For a complete


reference and examples, you can go to this
link<https://www.php.net/manual/en/funcref.php>.

User Defined Functions: Apart from built-in functions, We can also create
our own functions and call them easily.
A user-defined function looks something like this:

<?php
Function functionname(){
//Code
}
functionname(); // Calling Function
?>

Note: A function name should only start with letters and underscore only. It
can’t start with numbers and special symbols.

Example:
<?php
function helloMsg() {
echo "Hello world!";
}
helloMsg(); // call the function
?>

Function Arguments
Function Arguments: Argument is just like a variable which can be used to
pass through information to functions.
PHP supports Call by Value, Call by Reference, Default Argument Values
and Variable-length argument.

1. Call by Value

In Call by Value, the value of a variable is passed directly. This means if the
value of a variable within the function is changed, it does not get changed
outside of the function.
Example:

<?php
function incr($i)
{
$i++;
}
$i = 5;
incr($i);
echo $i;
?>

Copy
Output:

Copy

2. Call by Reference

In call by reference, the address of a variable (their memory location) is


passed. In the case of call by reference, we prepend an ampersand (&) to
the argument name in the function definition. Any change in variable value
within a function can reflect the change in the original value of a variable.
Example:

<?php
function incr&$i)
{
$i++;
}
$i = 5;
incr($i);
echo $i;
?>

Copy
Output:

Copy
3. Default Argument Values

If we call a function without arguments, then PHP function takes the default
value as an argument.
Example:

<?php
function Hello($name="Aakash"){
echo "Hello $name <br>";
}
Hello("Rohan");
Hello();//passing no value
Hello("Lovish");
?>

Copy
Output:

Hello Rohan
Hello Aakash
Hello Lovish

Copy

4. Variable Length Argument

It is used when we need to pass n number of arguments in a function. To


use this, we need to write three dots inside the parenthesis before the
argument.
Example:

<?php
function add(...$nums) {
$sum = 0;
foreach ($nums as $n) {
$sum += $n;
}
return $sum;
}
echo add(1, 2, 3, 4);
?>

Copy
Output:

10

Arrays
An array is a collection of data items of the same data type. And it is also
known as a subscript variable.
Example:

<?php
$age = array("Virat"=>"35", "Arshdeep"=>"37", "Rohit"=>"43");
echo "Virat is " . $age['Virat'] . " years old.";
?>

Copy

There are three different kinds of arrays.


1. Numeric Array

These are arrays with a numeric index where values are stored and
accessed in a linear fashion.
Example:

<?php
$bike = array("TVS", "YAMAHA", "RAJDOOT");
echo "I like " . $bike[0] . ", " . $bike[1] . " and " .
$bike[2] . ".";
?>

Copy

2. Associative Array

These are arrays with string as an index where it stores element values
associated with key values.
Example:

<?php
$age = array("Ben"=>"35", "Stokes"=>"37", "Jimi"=>"43");
echo "Ben is " . $age['Ben'] . " years old.";
?>

Copy

3. Multidimensional Arrays

A multidimensional Array is an array containing one or more arrays where


values are accessed using multiple indices.
Example:

<?php
$cars = array (
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
echo $cars[0][0].": In stock: ".$cars[0][1].", sold:
".$cars[0][2].".<br>";
?>

You might also like