Professional Documents
Culture Documents
aknu bsc 5th sem php unit 1
aknu bsc 5th sem php unit 1
PHP INTRODUCTION:
PHP, which stands for Hypertext Preprocessor, is a popular programming language used for web
development. Here are some key points about PHP in simple terms:
1. Purpose: PHP is mainly used to create dynamic and interactive websites.
It can generate dynamic page content, interact with databases, handle forms, manage
cookies, and more.
3. Integration: PHP can be integrated with various databases like MySQL, PostgreSQL, SQLite,
etc., to store and retrieve data. It can also be used with other technologies such as HTML, CSS, and
JavaScript to create complete web applications.
4. Syntax: PHP syntax is similar to C, Java, and Perl, making it relatively easy to learn if you're
familiar with any of these languages.
It uses <?php ... ?> tags to enclose its code, which can be embedded directly into HTML or used to
generate HTML dynamically.
5. Open Source: PHP is open-source, meaning it's free to use and widely supported by a large
community of developers.
Overall, PHP is valued for its simplicity, flexibility, and capability to handle a wide range of web
development tasks, from small personal websites to large-scale enterprise applications.
Charactersitics of php:
Five important characteristics make PHP's practical nature possible:
Simplicity
Efficiency
Security
Flexibility
Familiarity
Variables:
Variables are used allows programmers to store, manipulate, and retrieve values or information
within a program. Variables can hold different types of data such as numbers, text, boolean values
(true or false), arrays (collections of data), and more complex structures.
* A variable in PHP is denoted with a dollar sign ($) followed by the variable name.
For example: $name or $age.
* In php you don't need to declare the data type when you create a variable. PHP automatically
assigns the data type based on the value assigned to it.
* Must start with a letter or underscore
Example:
$name = "John";
$age = 30;
$isStudent = true;
PHP variables can be one of four scope types:
Local variables
Function parameters
Global variables
Static variables
Local variable
The variables that are declared within a function are called local variables for that function. These
local variables have their scope only in that particular function in which they are declared. This
means that these variables cannot be accessed outside the function, as they have local scope.
EXAMPLE:
<?php
function local_var()
{
$num = 45; //local variable
echo "Local variable declared inside the function is: ". $num;
}
local_var();
?>
Output;
Local variable declared inside the function is: 45
Global variable
The global variables are the variables that are declared outside the function. These variables can be
accessed anywhere in the program. To access the global variable within a function, use the
GLOBAL keyword before the variable. However, these variables can be directly accessed or used
outside the function without any keyword. Therefore there is no need to use any keyword to access
a global variable outside the function.
Example:
<?php
•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
exapmle:$x = "Hello world!";
$y = 'Hello world!';
PHP Integer
Example
$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: $x = 10.365;
var_dump($x);
PHP Boolean
• A Boolean represents two possible states: TRUE or FALSE.
• Booleans are often used in conditional testing
example: $x = true;
var_dump($x);
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:$cars = array("Volvo","BMW","Toyota");
var_dump($cars);A
Object:
An object type is an instance of a programmer-defined class, which can package up both other kinds
of values and functions that are specific to the class.
To create a new object, use the new statement to instantiate a class −
class foo
{
function bar()
{
echo "Hello World.";
}
}
$obj = new foo;
$obj->bar();
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.
• 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:
$x = "Hello world!";
$x = null;
var_dump($x);
output:NULL
Resources are special variables that hold references to resources external to PHP (such as a file
stream or database connections).
Here is an example of file resource −
Operators:
What is Operator?
Simple answer can be given using expression 4 + 5 is equal to 9. Here 4 and 5 are called operands
and + is called operator. PHP language supports following type of operators.
• Arithmetic Operators
• Comparison Operators
• Logical (or Relational) Operators
• Assignment Operators
• Conditional (or ternary) Operators
ArithmeticOperators
The following arithmetic operators are supported by PHP language: Assume variable A holds 10
and variable B holds 20 then:
Increment operator,
++ A++ will give 11
increases integer value by one
Example:
<?php
echo (5 % 3)."\n"; // prints 2
echo (5 % -3)."\n"; // prints 2
echo (-5 % 3)."\n"; // prints -2
echo (-5 % -3)."\n"; // prints -2
?>d able has not been assigned any value yet. Example: $variable =
Comparsion operator:::
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
Returns true if $x is equal to $y, and they are of the same
=== Identical $x === $y
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
Returns true if $x is not equal to $y, or they are not of the
!== Not identical $x !== $y
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
>= $x >= $y Returns true if $x is greater than or equal to $y
or equal to
Less than or
<= $x <= $y Returns true if $x is less than or equal to $y
equal to
<=> Spaceship $x <=> $y Returns an integer less than, equal to, or greater than zero,
depending on if $x is less than, equal to, or greater than $y.
Introduced in PHP 7.
Example:
<?php
var_dump(0 == "a");
var_dump("1" == "01");
var_dump("10" == "1e1");
var_dump(100 == "1e2");
switch ("a") {
case 0:
echo "0";
break;
case "a":
echo "a";
break;
}
?>
Logical Operators
The PHP logical operators are used to combine conditional statements.
Assignment Operators
The PHP assignment operators are used with numeric values to write a value to a 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.
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).
Branching statment:
• switch: Evaluates an expression against multiple possible values and executes the
corresponding block of code for the first match.
• The switch statement is used to perform different actions based on different
conditions
This is how it works:
i. The expression is evaluated once
ii. The value of the expression is compared with the values of each case
iii. If there is a match, the associated block of code is executed
iv. The break keyword breaks out of the switch block
v. The default code block is executed if there is no match
example:
$favcolor = "red";
switch ($favcolor)
{
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break; case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
2. Looping Statements:
Often when you write code, you want the same block of code to run over and over again a
certain number of times. So, instead of adding several almost equal code-lines in a script, we
can use loops.
Loops are used to execute the same block of code again and again, as long as a certain condition is
true.
In PHP, we have the following loop types:
• while: Executes a block of code as long as a specified condition is true.
Example: $i = 1;
while ($i < 6)
{
echo $i;
$i++;
}
The while loop does not run a specific number of times, but checks after each iteration if the
condition is still true.
• do...while: Similar to while, but guarantees the block of code is executed at least
once before checking the condition.
The do...while loop - Loops through a block of code once, and then repeats the loop
as long as the specified condition is true.
Example;$i = 1;
do
{
echo $i;
$i++;
}
while ($i < 6);
• for: Executes a block of code a specified number of times, with control over
initialization, condition, and incrementation.
This is how it works:
• expression1 is evaluated once
• expression2 is evaluated before each iteration
• expression3 is evaluated after each iteration
example:for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
• foreach: Iterates over arrays and objects, executing a block of code for each element.
The most common use of the foreach loop, is to loop through the items of
an array.
Loop through the items of an indexed array
example:
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $x)
{
echo "$x <br>";
}
3. Jump Statements:
• break: Terminates the current loop or switch statement and transfers control to the
statement immediately following the terminated statement.
Example:
for ($x = 0; $x <= 10; $x++)
{
if($x= =3) break;
echo "The number is: $x <br>";
}
• continue: Skips the rest of the current loop iteration and continues with the next
iteration.
Example:
for ($x = 0; $x <= 10; $x++)
{
if($x= =3) continue;
echo "The number is: $x <br>";
}
CODE BLOCK:
In PHP, a code block refers to a group of statements that are enclosed within curly braces {}.
These blocks are used to group together multiple statements that should be treated as a single unit
for control structures like functions, loops, conditional statements, classes, and more. Here's a
simple and clear explanation of code blocks in PHP
Key Points:
• Syntax: Code blocks in PHP are enclosed within curly braces {}.
• Purpose: They group multiple statements into a single unit for control structures like
functions, loops, conditional statements, and classes.
• Execution: The statements within a code block are executed sequentially whenever the
enclosing structure (function, loop, etc.) is executed.
Understanding code blocks in PHP is fundamental to organizing and controlling the flow of
execution within your scripts, making them clearer and easier to maintain.
FUNCTIONS:
• The real power of PHP comes from its functions.
• PHP has more than 1000 built-in functions, and in addition you can create your own custom
functions.
• a function is a block of reusable code that performs a specific task
• They encapsulate a set of instructions that can be called multiple times within a PHP script,
promoting code reusability and modularity.
• Functions are defined using the function keyword followed by a name and parentheses
()
Create a Function
A user-defined function declaration starts with the keyword function, followed by the name
of the function.
EXAMPLE:
function myMessage()
{
echo "Hello world!";
}
Call a Function
To call the function, just write its name followed by parentheses ():
EXAMPLE:
function myMessage()
{
echo "Hello world!";
}
myMessage() //calling function
Arguments:
In PHP, arguments (also referred to as parameters) are values that you pass to a function when you
call it. They allow you to provide input to the function, which the function can then use to perform
its tasks or calculations. Understanding how arguments work in PHP is crucial for creating flexible
and reusable functions.
Information can be passed to functions through arguments. An argument is just like a variable.
Arguments are specified after the function name, inside the parentheses. You can add as many
arguments as you want, just separate them with a comma.
The following example has a function with one argument ($fname). When
the familyName() function is called, we also pass along a name, e.g. ("Jani"), and the name is used
inside the function, which outputs several different first names, but an equal last name:
example:
function familyName($fname)
{
echo "$fname Refsnes.<br>";
}
familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName("KaiJim");