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

Class-10-Static Variables Print and Echo Statement Data Types String Functions Constants Operators Conditional Statements Loops

The document discusses PHP concepts like static variables, echo and print statements, data types, operators, and functions. Static variables allow a local variable's value to persist between function calls. Echo and print output text or variables. Data types include strings, integers, floats, booleans, arrays, objects, null, and resources. Operators perform operations on variables and values. Functions like strlen() and str_replace() manipulate strings.

Uploaded by

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

Class-10-Static Variables Print and Echo Statement Data Types String Functions Constants Operators Conditional Statements Loops

The document discusses PHP concepts like static variables, echo and print statements, data types, operators, and functions. Static variables allow a local variable's value to persist between function calls. Echo and print output text or variables. Data types include strings, integers, floats, booleans, arrays, objects, null, and resources. Operators perform operations on variables and values. Functions like strlen() and str_replace() manipulate strings.

Uploaded by

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

PHP Notes – Page : 6

PHP The static Keyword


Normally, when a function is completed/executed, all of its variables are deleted. However,
sometimes we want a local variable NOT to be deleted. We need it for a further job.
To do this, use the static keyword when you first declare the variable. A static variable will be
initialized only once, when the program control enters for the first time into the function and the
variable declaration statement is executed.
Example
<?php
function myTest()
{
static $x = 0;
echo "The value of the variable is : $x <br> ";
$x++;
}
myTest();
myTest();
myTest();
?> Then, each time the function is called, that variable will still have the information it contained
from the last time the function was called.
So, the output will be,

The value of the variable is : 0


The value of the variable is : 1
The value of the variable is : 2

Note: The variable is still local to the function.

PHP echo and print Statements


In PHP there are two basic ways to get output: echo and print.
echo and print are more or less the same. They are both used to output data to the screen.
The differences are small: echo has no return value while print has a return value of 1 so it can be
used in expressions. echo can take multiple parameters (although such usage is rare) while print
can take one argument. echo is marginally faster than print.
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. In the following example, <h2> is called the Heading tag, used to
display a heading. ie., to display the text in a bigger font size. The value after ‘h’ (ie., from 1 to
6), can be used to specify the heading size. The tag ends with </h2>.
Example
<?php
echo "<h2>PHP is Fun!</h2>";
echo "Hello world!<br>";
echo "I'm learning PHP!<br>";
PHP Notes – Page : 7

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 = "at L B S Centre.";
$x = 5;
$y = 4;
echo "<h2>$txt1</h2>";
echo "Study PHP $txt2<br>";
echo $x + $y;
?>
Output
Learn PHP
Study PHP at L B S Centre.
Study PHP at L B S Centre.
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 studying PHP!";
?>
OUTPUT
PHP is Fun!
Hello world!
I'm studying PHP!

Display Variables
The following example shows how to output text and variables with the print statement:
Example
<?php
$txt1 = "Learn PHP";
$txt2 = "L B S Centre.";
$x = 5;
$y = 4;
print "<h2>$txt1</h2>";
print "Study PHP at $txt2<br>";
PHP Notes – Page : 8

print $x + $y;
?>
PHP Data Types
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, must not have a decimal point and can be either
positive or negative
Example
<?php
$x = 5985;
var_dump($x);
?>
Output - int(5985)
PHP Float
A float (floating point number) is a number with a decimal point or a number in exponential
form.
PHP Boolean
A Boolean represents two possible states: TRUE or FALSE.
$x = true;
$y = false;
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 Notes – Page : 9

<?php
$cars = array("Maruti","Tata",”Leyland");
var_dump($cars);
?>
OUTPUT

array(3) { [0]=> string(6) "Maruti" [1]=> string(4) "Tata" [2]=> string(7) "Leyland" }

PHP Object
An object is a data type which stores data and information on how to process that data.
In PHP, an object must be explicitly declared.
First we must declare a class of object. For this, we use the class keyword.
Example
<?php
class Car {
function Car() {
$this->model = " Maruti Alto";
}
}
// create an object
$Mycar = new Car();
// show object properties
echo $Mycar->model;
?>
Output - Maruti Alto

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

NULL

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.
A common example of using the resource data type is a database call.
PHP Notes – Page : 10

PHP String Functions


strlen() - Get The Length of a String
The PHP strlen() function returns the length of a string.
The output of the code above will be: 12.
str_word_count() - Count The Number of Words in a String
The PHP str_word_count() function counts the number of words in a string:
strrev() - Reverse a String
The PHP strrev() function reverses a string:
strpos() - Search For a Specific Text Within a String
The PHP strpos() function searches for a specific text within a string.
If a match is found, the function returns the character position of the first match. If no match is
found, it will return FALSE.
Tip: The first character position in a string is 0 (not 1).
str_replace() - Replace Text Within a String
The PHP str_replace() function replaces some characters with some other characters in a string.
The example below replaces the text "world" with "Friends":
Example
<?php
$x = "Hello world!";
echo "The string is : ".$x;
echo "<br>String Length :".strlen("Hello world!"); // output - 12
echo "<br>Number of words in the string : ".str_word_count("Hello world!");
// output - 2
echo "<br>The reversed string is : ".strrev("Hello world!");
// output - !dlrow olleH
echo "<br>Position of the text 'word' in the string is : ".strpos("Hello world!", "world");
//output - 6
echo "<br>The string after replacing the word 'world' with the word 'friend' is :
".str_replace("world", "Friends", "Hello world!"); // output - Hello Friends!
?>
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.
Create a PHP Constant
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
The example below creates a constant with a case-sensitive name:
PHP Notes – Page : 11

Example
<?php
define("GREETING", "Welcome to LBS Centre!");
echo GREETING;
?>
The example below creates a constant with a case-insensitive name:
Example
<?php
define("GREETING", "Welcome to LBS Centre!", true);
echo greeting;
?>

The example below uses a constant inside a function, even if it is defined outside the function:
Example
<?php
define("GREETING", "Welcome to LBS Centre!");
function myTest() {
echo GREETING;
}
myTest();
?>
PHP Operators
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
<html>
<body>
<?php
$x = 10;
PHP Notes – Page : 12

$y = 3;
echo $x + $y; // output - 13
echo $x - $y; // output - 7
echo $x * $y; // output - 30
echo $x / $y; // output - 3.3333333333333
echo $x % $y; // output - 1
echo $x ** $y; // output - 1000
?>
</body>
</html>

PHP 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.
Assignment Same as... Description
x=y x=y left operand gets set to value of the expression on the right
x += y x = x + y Addition left operand gets set to value of the expression on the right
x -= y x = x - y Subtraction left operand gets set to value of the expression on the right
x *= y x = x * y Multiplication left operand gets set to value of the expression on the right
x /= y x = x / y Division left operand gets set to value of the expression on the right
x %= y x = x % y Modulus left operand gets set to value of the expression on the right

PHP Comparison Operators


The PHP comparison operators are used to compare two values (number or string):
Operator Name Example Result
== Equal(2 = signs) $x == $y Returns true if $x is equal to $y
Identical Returns true if $x is equal to $y, and they are of the
=== $x === $y
(3 = signs) 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 Returns true if $x is not equal to $y, or they are not of
!== $x !== $y
(2 = signs) 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 $y
equal to
Less than or equal
<= $x <= $y Returns true if $x is less than or equal to $y
to

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.
PHP Notes – Page : 13

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.
Operator Name Example Result
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

PHP String Operators


PHP has two operators that are specially designed for strings.
Operator Name Example Result
Concatenation of $txt1
. Concatenation $txt1 . $txt2
and $txt2
.= Concatenation assignment $txt1 .= $txt2 Appends $txt2 to $txt1

PHP Array Operators


The PHP array operators are used to compare arrays.
Operator Name Example Result
+ Union $x + $y Union of $x and $y
Returns true if $x and $y have the same
== Equality $x == $y
key/value pairs
Returns true if $x and $y have the same
=== Identity $x === $y 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 Statements
To perform different actions for different conditions, you can use conditional statements in the
code.
In PHP we have the following conditional statements:
 if statement - executes some code if one condition is true
PHP Notes – Page : 14

 if...else statement - executes some code if a condition is true and another code if that
condition is false
 if...elseif....else statement - executes different codes for more than two conditions
 switch statement - selects one of many blocks of code to be executed
PHP - The if Statement
The if statement executes some code if one condition is true.
Syntax
if (condition) {
code to be executed if condition is true;
}
The example below will output "Have a good day!" if the current time (HOUR) is less than 20:
Example
<?php
$t = date("H"); //H is 24 hour format of the current time, taken from the date.
if ($t < "20") {
echo "Have a good day!";
}
?>
PHP - The if...else Statement
The if....else statement executes some code if a condition is true and another code if that
condition is false.
Syntax
if (condition)
{
code to be executed if condition is true;
}
else
{
code to be executed if condition is false;
}
The example below will output "Have a good day!" if the current time is less than 20, and "Have
a good night!" otherwise:
Example
<?php
$t = date("H");

if ($t < "20")


{
echo "Have a good day!";
}
else
{
echo "Have a good night!";
}
?>
PHP - The if...elseif....else Statement
PHP Notes – Page : 15

The if....elseif...else statement executes different codes for more than two conditions.
Syntax
if (condition1)
{
code to be executed if this condition1 is true;
}
elseif (condition2)
{
code to be executed if this condition2 is true;
}
else
{
code to be executed if all conditions are false;
}
The example below will output "Have a good morning!" if the current time is less than 10, and
"Have a good day!" if the current time is less than 20. Otherwise it will output "Have a good
night!":
Example
<?php
$t = date("H");
if ($t < "10")
{
echo "Have a good morning!";
}
Elseif
($t < "20")
{
echo "Have a good day!";
}
else
{
echo "Have a good night!";
}
?>
PHP switch Statement

The switch statement is used to perform different actions based on different conditions.
Use the switch statement to select one of many blocks of code to be executed.
Syntax
switch (n)
{
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
PHP Notes – Page : 16

break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}
This is how it works: First we have a single expression n (most often a variable), that is
evaluated once. The value of the expression is then compared with the values for each case in the
structure. If there is a match, the block of code associated with that case is executed. Use break
to prevent the code from running into the next case automatically. The default statement is used
if no match is found.
Example
<?php
$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!";
}
?>
PHP Loops
Often when you write code, you want the same block of code to run over and over again in a
row. Instead of adding several almost equal code-lines in a script, we can use loops to perform a
task repeatedly.
In PHP, we have the following looping statements:
 while - loops through a block of code as long as the specified condition is true
 do...while - loops through a block of code once, and then repeats the loop as long as the
specified condition is true
 for - loops through a block of code a specified number of times
 foreach - loops through a block of code for each element in an array
The PHP while Loop – Entry controlled loop
The while loop executes a block of code as long as the specified condition is true.
Syntax
while (condition is true)
PHP Notes – Page : 17

{
code to be executed;
}
The example below first sets a variable $x to 1 ($x = 1). Then, the while loop will continue to
run as long as $x is less than, or equal to 5 ($x <= 5). $x will increase by 1 each time the loop
runs ($x++):
Example
<?php
$x = 1;
while($x <= 5)
{
echo "The number is: $x <br>";
$x++;
}
?>
The PHP do...while Loop - Exit controlled loop
The do...while loop will always execute the block of code once, it will then check the condition,
and repeat the loop while the specified condition is true.
Syntax
Do
{
code to be executed;
}
while (condition is true);
The example below first sets a variable $x to 1 ($x = 1). Then, the do while loop will write some
output, and then increment the variable $x with 1. Then the condition is checked (is $x less than,
or equal to 5?), and the loop will continue to run as long as $x is less than, or equal to 5:
Example
<?php
$x = 1;
do
{
echo "The number is: $x <br>";
$x++;
}
while ($x <= 5);
?>
Notice that in a do while loop the condition is tested AFTER executing the statements within the
loop. This means that the do while loop would execute its statements at least once, even if the
condition is false the first time.
The example below sets the $x variable to 6, then it runs the loop, and then the condition is
checked:
Example
<?php
$x = 6;
do
PHP Notes – Page : 18

{
echo "The number is: $x <br>";
$x++;
}
while ($x <= 5);
?>
The PHP for Loop
The for loop is used when you know in advance how many times the script should run.
Syntax
for (init counter; test counter; increment counter)
{
code to be executed;
}
Parameters:
 init counter: Initialize the loop counter value
 test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop
continues. If it evaluates to FALSE, the loop ends.
 increment counter: Increases the loop counter value
The example below displays the numbers from 0 to 10:
Example
<?php
for ($x = 0; $x <= 10; $x++)
{
echo "The number is: $x <br>";
}
?>
The PHP foreach Loop
The foreach loop works only on arrays, and is used to loop through each key/value pair in an
array.
Syntax
foreach ($array as $value)
{
code to be executed;
}
For every loop iteration, the value of the current array element is assigned to $value and the array
pointer is moved by one, until it reaches the last array element.
The following example demonstrates a loop that will output the values of the given array
($colors):
Example
<?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $value)
{
echo "$value <br>";
}
?>
PHP Notes – Page : 19

PHP Functions
The real power of PHP comes from its functions; it has more than 1000 built-in functions.
PHP User Defined Functions
Besides the built-in PHP functions, we can create our own functions.
A function is a block of statements that can be used repeatedly in a program.
A function will not execute immediately when a page loads.
A function will be executed by a call to the function.
Create a User Defined Function in PHP
A user defined function declaration starts with the word "function":
Syntax
Function functionName()
{
code to be executed;
}
Note: A function name can start with a letter or underscore (not a number). Function names are
NOT case-sensitive.
In the example below, we create a function named "writeMsg()". The opening curly brace ( { )
indicates the beginning of the function code and the closing curly brace ( } ) indicates the end of
the function. The function outputs "Hello Welcome to PHP Programming!". To call the function,
just write its name:
Example.
<?php
function writeMsg()
{
echo "Hello world!";
}
writeMsg(); // call the function
?>
PHP Function Arguments
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 seperate them with a comma.
The following example has a function with one argument ($studentname). When the
centreName() 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
<?php
function centreName($studentname)
{
echo "$studentname is a student of LBS Centre, Kalamassery.<br>";
}
centreName ("Prasad");
centreName ("Hari");
centreName ("Seema");
centreName ("Kamal");
PHP Notes – Page : 20

centreName ("Ameena");
?>
The following example has a function with two arguments ($studentname and $course):
Example
<?php
function centreName($studentname, $course) {
echo "$studentname is a student of LBS Centre, Kalamassery. Studying the course
$course<br>";
}
centreName ("Prasad",”PGDCA”);
centreName ("Hari",”DCA”);
centreName ("Seema",”PGDCA”);
centreName ("Kamal",”PGDCA”);
centreName ("Ameena",”DCA”);
?>
PHP Functions - Returning values
To let a function return a value, use the return statement:
Example
<?php
function sum($x, $y)
{
$z = $x + $y;
return $z;
}
echo "5 + 10 = " . sum(5, 10) . "<br>";
echo "7 + 13 = " . sum(7, 13) . "<br>";
echo "2 + 4 = " . sum(2, 4);
?>

You might also like