Variables, Data Types, Statements, Operators, Loops

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 59

Php

VARIABLES, DATA TYPES, STATEMENTS, OPERATORS,


LOOPS
Php variables

 Variable is a symbol or name that stands for a value. Variables


are used for storing values such as numeric values, characters,
character strings, or memory addresses so that they can be used
in any part of the program.
 Syntax to declare variable in php
 $variablename=value;
 A variable can have a short name (like a and b) or a more
descriptive name (like name, age, areaofcircle, total_marks)
Example of variable in php

<!DOCTYPE html>
<html>
<body>

<?php
$x = 5;
$y = 4;
echo $x + $y;
?>

</body>
</html>
Declaring PHP variables

 All variables in PHP start with a $ (dollar) sign followed by the


name of the variable.
 A valid variable name starts with a letter (A-Z, a-z) or underscore
(_), followed by any number of letters, numbers, or underscores.
 If a variable name is more than one word, it can be separated
with an underscore (for example $employee_code instead of
$employeecode).
 '$' is a special variable that can not be assigned.
type casting and type
juggling.
 The way by which PHP can assign a particular data type for any
variable is called typecasting. The required type of variable is
mentioned in the parenthesis before the variable.
$str = "10"; // $str is now string
$bool = (boolean) $str; // $bool is now Boolean
 PHP does not support data type for variable declaration. The type
of the variable is changed automatically based on the assigned
value and it is called type juggling.
$val = 5; // $val is now number
$val = "500" //$val is now string
PHP Constants

 A constant is a name or an identifier for a fixed value. Constant


are like variables, except that once they are defined, they cannot
be undefined or changed (except magic constants).
 Constants are very useful for storing data that doesn't change
while the script is running. Common examples of such data
include configuration settings such as database username and
password, website's base URL, company name, etc.
 Constants are defined using PHP's define() function, which
accepts two arguments: the name of the constant, and its value.
Once defined the constant value can be accessed at any time
just by referring to its name.
 Example:
<?php
define("GREETING", "Welcome to W3Schools.com!");
echo GREETING;
?>
Constant Arrays

 In PHP7, you can create a Array constant using the define() function.
 The example below creates an Array constant:
 Example:
<?php
define("cars", [
"Alfa Romeo",
"BMW",
"Toyota"
]);
echo cars[0];
?>
Constants are Global

 Constants are automatically global and can be used across the entire
script.
 The example below uses a constant inside a function, even if it is
defined outside the function:
 Example:
<?php
define("GREETING", "Welcome to W3Schools.com!");
function myTest() {
echo GREETING;
}
myTest();
?>
PHP Magic Constants

 PHP moreover also provide a set of special predefined constants


that change depending on where they are used. These constants
are called magic constants. For example, the value of __LINE__
depends on the line that it's used on in your script.

 Magic constants begin with two underscores and end with two
underscores. The following section describes some of the most
useful magical PHP constants.
 __LINE__
The __LINE__ constant returns the current line number of the file,
like this:
Example
<?php
echo "Line number " . __LINE__ . "<br>"; // Displays: Line number 2
echo "Line number " . __LINE__ . "<br>"; // Displays: Line number 3
echo "Line number " . __LINE__ . "<br>"; // Displays: Line number 4
?>
 __FILE__
The __FILE__ constant returns full path and name of the PHP file
that's being executed. If used inside an include, the name of the
included file is returned.
 Example
<?php
// Displays the absolute path of this file
echo "The full path of this file is: " . __FILE__;
?>
 __DIR__
The __DIR__ constant returns the directory of the file. If used inside
an include, the directory of the included file is returned. Here's an
example:

 Example
<?php
// Displays the directory of this file
echo "The directory of this file is: " . __DIR__;
?>
 __FUNCTION__
The __FUNCTION__ constant returns the name of the current function.

 Example
<?php
function myFunction(){
echo "The function name is - " . __FUNCTION__;
}
myFunction(); // Displays: The function name is - myFunction
?>
 __CLASS__
The __CLASS__ constant returns the name of the current class. Here's an example:
 Example
<?php
class MyClass
{
public function getClassName(){
return __CLASS__;
}
}
$obj = new MyClass();
echo $obj->getClassName(); // Displays: MyClass
?>
 __METHOD__
The __METHOD__ constant returns the name of the current class method.
 Example
<?php
class Sample
{
public function myMethod(){
echo __METHOD__;
}
}
$obj = new Sample();
$obj->myMethod(); // Displays: Sample::myMethod
?>
 __NAMESPACE__
The __NAMESPACE__ constant returns the name of the current namespace.
 Example
<?php
namespace MyNamespace;
class MyClass
{
public function getNamespace(){
return __NAMESPACE__;
}
}
$obj = new MyClass();
echo $obj->getNamespace(); // Displays: MyNamespace
?>
Data Types in PHP
 PHP has a total of 8 Data Types which we use to declare variables:
 Integer: are the whole number, without a decimal point, eg. $var = 12345;
 Double: are floating-point number can contain decimal number, eg. $num =
2.2888800;
 Boolean: can have only two possible values, true or false, eg. $x = true. Boolean
value are often used in condition testing.
 NULL: is a special type that only has one value:NULL, eg. $my_var = NULL.
 String: is a collection of characters, eg. $str = "This is a string". A string can be
any text inside quotes. You can use single or double quotes to represent a string.
 Arrays: An array stores multiple values in one single variable, eg. $colors =
array("Red","Green","Blue");
 Objects: are instances of a class, which can package up both kinds of values and
functions that are specific to the class.
 Resources: are special variables that hold references to resources external to
PHP (such as database connections).
Difference between echo and
print in PHP
 PHP echo and print both are PHP Statement.
 Both are used to display the output in PHP.
 echo
 echo is a statement i.e used to display the output. it can be used with
parentheses echo or without parentheses echo.
 echo can pass multiple string separated as ( , )
Echo "This ", "string ", "was ", "made ", "with multiple parameters ",
"separated with comma (\,)" ;
 echo doesn’t return any value
$r = echo $name; //Error
 echo is faster then print
 Print
 Print is also a statement i.e used to display the output. it can be used
with parentheses print( ) or without parentheses print.
 using print can doesn’t pass multiple argument.
print "Hello ", "World"; //Error
 print always return 1.  So it can be used in expressions.
 it is slower than echo
Examples

 Echo  Print
<?php <?php
// Displaying HTML code // Displaying HTML code
echo "<h4>This is a simple print "<h4>This is a simple
heading.</h4>"; heading.</h4>";
echo "<h4 style='color: red;'>This print "<h4 style='color: red;'>This
is heading with style.</h4>"; is heading with style.</h4>";
?> ?>
Embedding HTML inside Embedding PHP Inside
PHP HTML

<?php <?php
$date = 26; $text= "Enter username";
$month = "January"; ?>
echo "Republic Day is on ".$date." <input type="text" value="<?php
".$month.""; echo $text; ?>">
?>
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

+ Addition $a + $b

- Subtraction $a - $b

* Multiplication $a * $b

/ Division $a/ $b

% Modulus $a% $b
 Arithmetic Addition Operator
$a= 10;  
$b = 6;
echo $c =  $a+ $b;
 Arithmetic Subtraction Operator
$a= 10;  
$b = 6;
echo $a- $b;
 Arithmetic Multiple Operator
$a= 10;  
$b = 6;
echo $a* $b;
 Arithmetic Division Operator
$a= 10;  
$b = 6;
echo $a/ $b;
 Arithmetic Modulus Operator
$a= 10;  
$b = 6;
echo $a% $b;
PHP Assignment Operators

 The PHP assignment


operators are used with
numeric values to write a
Operato Same Description value to a variable.
r use like
x=y x=y The right variable assign value on
the Left variable
x += y x = x +y Addition
x -= y x = x –y Subtraction
x *= y x = x *y Multiplication
x /= y x = x /y Division
x %= y x = x %y Modulus/Remainder
 Examples:
$a= 10;  
echo $a; 

$a= 20;  
$a+= 100;
echo $a; 

$a= 50;
$a-= 30;
echo $a;

$a= 5;
$a*= 6;
echo $a;

$a= 10;
$a/= 5;
echo $a;

$a= 15;
$a%= 4;
echo $a;
PHP Comparison
Operators Operato Name Exampl Result
r e
== Equal $a== $b Returns true if $a is equal to $b
=== Identical $a=== Returns true if $a is equal to $b, and
$b they are of the same type
 The PHP comparison
operators are used to != Not equal $a!=$b Returns true if $a is not equal to $b
compare two values !== Not identical $a!==$b Returns true if $a is not equal to $b, or
(number or string) they are not of the same type
>  Greater than $a> $b Returns true if $a is greater than $b
<  Less than $a < $b Returns true if $a is less than $b
>= Greater than $a >= Returns true if $a is greater than or
or equal to $b equal to $b
<= Less than or $a <= Returns true if $a is less than or equal
equal to $b to $b
 Equal
$a = 100;  
$b = "100";
var_dump($a == $b); // returns true because values are equal
 Identical (Exact Equal)
$a = 100;  
$b = "100";
var_dump($a === $b); // returns false because types are not equal
 Not equal
$a = 100;  
$b = "100";
var_dump($a != $b); // returns false because values are equal
 Not identical
$a = 100;  
$b = "100";
var_dump($a !== $b); // returns true because types are not equal
 Less than or equal to
$a = 50;
$b = 50;
var_dump($a <= $b); // returns true because $a is less than or equal to $b
 Greater than
$a = 100;
$b = 50;
var_dump($a > $b); // returns true because $a is greater than $b 
 Less than
$a = 10;
$b = 50;
var_dump($a < $b); // returns true because $a is less than $b
 Greater than or equal to
$a = 50;
$b = 50;
var_dump($a >= $b); // returns true because $a is greater than or equal
to $b
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.
Operator Name Description

++$a Pre-increment Increments $a by one,


then returns $a

$a++ Post-increment Returns $a, then


increments $a by one

--$a Pre-decrement Decrements $a by one,


then returns $a

$a-- Post-decrement Returns $a, then


decrements $a by one
 Pre-increment
$a = 10;  
echo ++$a;
 
 Post-increment
$a = 10;  
echo $a++;
 
 Pre-decrement
$a = 10;  
echo --$a;
 
 Post-decrement
$a = 10;  
echo $a--;
PHP Logical Operators

 The PHP logical operators are used to combine conditional


statements.

Operator Name Example Result


And And $a and $b True if both $a and $b are
true
Or Or $a or $b True if either $a or $b is true

&& And $a && $b True if both $a and $b are


true
|| Or $a || $b True if either $a or $b is true

! Not !$a True if $a is not true


 And
$a = 100;  
$b = 50;

if ($a == 100 and $b == 10) {


    echo "Hello world!";
}

 Or
$a = 100;  
$b = 50;

if ($a == 100 or $b == 80) {


    echo "Hello world!";
}
 And
$a = 100;  
$b = 50;

if ($a == 100 && $b == 50) {


    echo "Hello world!";
}
 
 Or
$a = 100;  
$b = 50;

if ($a == 100 || $b == 80) {


    echo "Hello world!";

 Not 
$a = 120;  
if ($a!== 120) {
    echo "Hello world!";
}
 
PHP String Operators

 PHP has two operators that are specially designed for strings.

Operat Name Example Result


or
. Concatenation $txt1 . $txt2 Concatenation
of $txt1 and
$txt2
.= Concatenation $txt1 .= $txt2 Appends $txt2
assignment to $txt1
PHP Array Operators

 The PHP array operators are used to compare arrays.

Operator Name Example Result


+ Union $a + $b Union of $a and $b
== Equality $a == $b Returns true if $a and $b have
the same key/value pairs
=== Identity $a === $b Returns true if $a and $b have
the same key/value pairs in the
same order and of the same
types
!= Inequality $a != $b Returns true if $a is not equal to
$b
!== Non-identity $a !== $b Returns true if $a is not identical
to $b
 $a = array("a" => "red", "b" => "green");  
$b = array("c" => "blue", "d" => "yellow");  
print_r($a + $b); // union of $a and $b 
 $a = array("a" => "red", "b" => "green");  
$b = array("c" => "blue", "d" => "yellow");  
var_dump($a == $b); 
 $a = array("a" => "red", "b" => "green");  
$b = array("c" => "blue", "d" => "yellow");  
var_dump($a === $b); 
 $a = array("a" => "red", "b" => "green");  
$b = array("c" => "blue", "d" => "yellow");  
var_dump($a != $b); 
 $a = array("a" => "red", "b" => "green");  
$b = array("c" => "blue", "d" => "yellow");  
var_dump($a !== $b);
PHP Conditional Statements

 PHP also allows you to write code that perform different actions
based on the results of a logical or comparative test conditions at
run time. This means, you can create test conditions in the form
of expressions that evaluates to either true or false and based on
these results you can perform certain actions.
 There are several statements in PHP that you can use to make
decisions:
 The if statement
 The if...else statement
 The if...elseif....else statement
 The switch...case statement
The if Statement

 The if statement is used to execute a block of code only if the


specified condition evaluates to true. This is the simplest PHP's
conditional statements and can be written like:
if(condition){
// Code to be executed
}
Example

<?php
$d = date("D");
if($d == "Fri"){
echo "Have a nice weekend!";
}
?>
The if...else Statement

 You can enhance the decision making process by providing an


alternative choice through adding an else statement to
the if statement. The if...else statement allows you to execute
one block of code if the specified condition is evaluates to true
and another block of code if it is evaluates to false. It can be
written, like this:
 if(condition){
// Code to be executed if condition is true
} else{ // Code to be executed if condition is false
}
Example

<?php
$d = date("D");
if($d == "Fri"){
echo "Have a nice weekend!";
} else{
echo "Have a nice day!";
}
?>
The if...elseif...else Statement

 The if...elseif...else a special statement that is used to combine


multiple if...else statements.
if(condition1){
// Code to be executed if condition1 is true
} elseif(condition2){
// Code to be executed if the condition1 is false and condition2 is
true
} else{
// Code to be executed if both condition1 and condition2 are false
}
Example

<?php
$d = date("D");
if($d == "Fri"){
echo "Have a nice weekend!";
} elseif($d == "Sun"){
echo "Have a nice Sunday!";
} else{
echo "Have a nice day!";
}
?>
switch statement

 switch statement is used if you want to select one of many blocks


of code to be executed, use the Switch statement. The switch
statement is used to avoid long blocks of if..elseif..else code.
Example: Switch condition.

$d=date("D echo "Today


<?php switch ($d) { case "Mon": break;
"); is Monday";

echo "Today
echo "Today is
case "Tue": break; case "Wed": break; case "Thu":
is Tuesday"; Wednesday
";

echo "Today echo "Today


echo "Today
is break; case "Fri": break; case "Sat": is
is Friday";
Thursday"; Saturday";

echo
echo "Today "Wonder
break; case "Sun": break; default: }
is Sunday"; which day
is this ?";

?>
difference between Print_r and
Var_dump?
 var_dump displays structured information about the object /
variable. print_r displays human readable information about the
values with a format presenting keys and elements for arrays
and objects. The most important thing to notice is var_dump will
output type as well as values while print_r does not.
PHP Loops

 Loops are use to repeat a block of code again and again upto
specified number of times. In PHP, there are 4 types of loops
available. They are: 
 for loop. 
 while loop.
 do...while loop.
 foreach loop.
PHP For Loop

 PHP for loop is divided into 3 parts i.e. initialization, condition and
increment/decrement. Initialization is the initial value from where
the loop start execution, condition will execute a loop till the
specified condition is true and quits the loop if it is false,
increment/decrement will change the variable value for the next
condition.
Example

 print counting 1 to 10 using For Loop


<html>
<body>
<?php
for( $i=1; $i<=10; $i++ )
{
echo "For Loop $i " ;
}
?>
</body>
</html> 
PHP While Loop

 PHP while loop is also used to repeat a block of code up to a


certain number of times, but the syntax is different, initialization
statement is defined before the loop begins, while loop condition
appears to test the loop, and increment/decrement statement
will appear inside the while loop.
Example

 print counting 1 to 10 using While Loop


<html>
<body>
<?php
$i=1;
while( $i <= 10)
{
echo "While Loop $i ";
$i++;
}
?>
</body>
</html>
PHP Do While Loop

 PHP do while loop is also used to repeat a block of code up to a


certain number of times, but the syntax is different, initialization
statement is defined before the loop begins,
increment/decrement will appear inside the do while loop and
condition appears at the last.
Example

 print counting 1 to 10 using Do While Loop


<html>
<body>
<?php
$i=1;
do
{
$i++;
echo "Do while loop $i ";
}while( $i <= 10 );
?>
</body>
</html> 
Difference Between while and
do…while Loop
 The while loop differs from the do-while loop in one important
way — with a while loop, the condition to be evaluated is tested
at the beginning of each loop iteration, so if the conditional
expression evaluates to false, the loop will never be executed.

 With a do-while loop, on the other hand, the loop will always be
executed once, even if the conditional expression is false,
because the condition is evaluated at the end of the loop
iteration rather than the beginning.
PHP foreach Loop

 The foreach loop is used to iterate over arrays.


syntax:
foreach($array as $value){
// Code to be executed
}
The following example demonstrates a loop that will print the values of
the given array:
Example 1 Example 2
<?php <?php
$superhero = array(
$colors = array("Red", "Green",
"name" => "Peter Parker",
"Blue");
"email" => "peterparker@mail.com",
"age" => 18
// Loop through colors array );

foreach($colors as $value){
// Loop through superhero array
echo $value . "<br>";
foreach($superhero as $key => $value){
} echo $key . " : " . $value . "<br>";

?> }
?>

You might also like