Swati Lathia

Learning ways

PHP Tutorials

PHP is the most popular web scripting language specially to create dynamic web pages / websites. PHP is a server side scripting language. Initially, PHP was “Personal Home Page“, developed by Rasmus Lerdorf. Now PHP stands for “Hypertext PreProcessor“.

PHP is very easy to use language for beginners for website development. It is a widely used & open source language. PHP is popularly used to create the majority of e-commerce websites, bloggers, any many other web applications.

PHP File

PHP files may contain simple text, HTML, CSS, JavaScript & PHP code itself.

On the server, PHP code is performed, and the result is sent to the browser as plain HTML.

This file is saved as .php extension in your web directory (For wamp server, C:/wamp/www is a default web directory)

Use of PHP

  • PHP is used to collect the data from HTML form.
  • PHP is used to insert, update & delete the data in database.
  • PHP is used to create a session on server side to identify the user.
  • PHP is used to send & receive the cookies on client’s computer.
  • PHP also works with AJAX to reduce loading time of whole page.

What do you need?

  • Find for a web host that supports PHP and MySQL.
  • Install a web server on your own PC, and then install PHP and MySQL.

You can also use WAMP which consists of Apache web server, MySQL database and PHP programming language. WAMP is used to host PHP pages.

Where to write PHP code?

PHP code can be written in notepad, notepad++, Dreamweaver or any other PHP designer editor. This file with PHP code has .php extension.

PHP Syntax

  • You can write PHP script/code anywhere in web page.
  • It start with <?php and ends with ?>
  • Apart from PHP code, file may contain HTML tags, JavaScript & CSS.
  • PHP statement must end with ; (semicolon).
  • In PHP, variable names are case-sensitive. Though, all user defined function name, classes, built in functions, keywords are not case sensitive.

For more practical information, See https://swatilathia.com/php-video-tutorial/#Introduction_to_PHP_How_to_save_PHP_file_How_to_write_PHP_code

<?php
       //Code here
?>

Comments in PHP

  • Comments are not a part of the program to be executed.
  • It is just to inform the user what the program is all about.
  • It allows people to comprehend your code.
  • It reminds you what you performed in the program so that when you check it, you easily understand what the program is about.
  • There are mainly 3 types of comments in PHP. Look at the following script:
<html>
<body>
<?php
      //This is Single line Comment
      # This is Unix Shell style single line comment
      /* Hello Students
         This is Swati Lathia
         & Here i am using Multiline comment
       */
?>
</body>
</html>

How to print/output in PHP (print)

In PHP, print is used to output a string.

print is not a function but a language construct. Its argument is the expression following the print keyword. print always returns 1.

<?php
	print "Hello World";
	
        //to new line use <br> in ""/''(double/single quotes)
	print "<br>";
	
        //to print the result of expression
	print (10+20)*30;
	/*Output of above statement is 900
	the parentheses cause 10+20 to be evaluated first
	then 30*30 and the print statement sees the whole      
	expression as one argument */
	
	//Every HTML tag can be used by ""/'' with print
	print "<br><font size=6 color=red>Hi Swati</font>";
?>

How to print/output in PHP (echo)

In PHP, to output one or more strings we can also use echo.

echo is not a function but a language construct. Its arguments are a list of expressions following the echo keyword, separated by commas. echo does not return any value.

The main differences between print and echo are that echo accepts multiple arguments and doesn’t have a return value.

<?php
echo "This does not require parentheses.";

//to print multiple arguments
echo '<br>This ', 'is ', 'Swati ', 'Lathia ', 'from HJD.';
	
/*concatenated together and passed as a single argument*/
echo '<br>This '. 'is '. 'Swati '. 'Lathia '. 'from HJD.';

//to new line use <br> in ""/''(double/single quotes)
echo "<br>";
	
//to output the result of expression
echo (10+20)*30;
/* Output of above statement is 900
the parentheses cause 10+20 to be evaluated first
then 30*30 and the echo statement sees the whole      
expression as one argument */
	
//Every HTML tag can be used by ""/'' with echo
echo "<br><font size=6 color=red>Hi Swati</font>";
?>

PHP Data Types

Since PHP is a dynamically typed language, there is no need to specify the type of a variable by default as it will be determined at runtime.

Depending on its value, PHP has one of the following built-in kinds:

  • null
  • bool
  • int
  • float (also called Double)
  • string
  • array
  • object
  • resource

PHP Variables

A PHP programme uses variables to store values or data that can be used at a later time. The variables are also containers that hold strings, memory addresses, character values, and numeric values. In PHP, to declare and store variables follow these rules:

  • Each variable declaration starts with a dollar sign ($), then the variable name.
  • PHP variable name must start with either alphanumeric characters or underscores (for example, ‘a-z’, ‘A-Z’, ‘0-9, and ‘_’) in their name.
  • PHP variable cannot start with a number.
  • PHP variable is case-sensitive. For example, $var and $VAR both are different.

For more practical information https://swatilathia.com/php-video-tutorial/#PHP_Variable_Data_Types

Let us take an example of variables and their different data type

<?php
        //initializing integer type of variable
	$total=80;
	echo "Total marks = ".$total."<br>";
	
	//initializing float/double variable
	$percent=70.67;
	echo "Percentage = ".$percent."<br>";
	
	//initializing string/charcater variable
	$name="Swati Lathia";
	echo "Hi this is ".$name."<br>";
	
	//initializing boolean variable
	//true is 1 and false is 0
	$flag=true;
	echo "The value of flag is = ".$flag;
?>
Output
Total marks = 80
Percentage = 70.67
Hi this is Swati Lathia
The value of flag is = 1

PHP Operators

  • Here, we are discussing mainly six types of operators of PHP : Arithmetic, Assignment, Comparision, Incrementing/Decrementing, Logical and String operators:
  • Let us start every operator with example of each one.

Arithmetic Operators

OperationExampleResult
Identity+$no1$no1 is converted to int or float as needed.
Negation-$no1Opposite of $no1
Addition$no1+$no2Sum of $no1 and $no2
Subtraction$no1-$no2Difference of $no1 and $no2
Multiplication$no1*$no2Multiply $no1 and $no2
Division$no1/$no2Quotient of $no1 and $no2
Modulo$no1%$no2Remainder of $no1 divided by $no2
Exponentiation$no1**$no2Result of raising $no1 to the power $no2

Assignment Operators

  • The basic assignment operator is “=”. 
  • Here we are discussing Arithmetic assignment operators with examples.
OperationExampleEquivalent to
Addition$n1+=$n2$n1=$n1+$n2
Subtraction$n1-=$n2$n1=$n1-$n2
Multiplication$n1*=$n2$n1=$n1*$n2
Division$n1/=$n2$n1=$n1/$n2
Modulus$n1%=$n2$n1=$n1%$n2
Exponentiation$n1**=$n2$n1=$n1**$n2
String Concatenation
(Joins two or more strings)
$n1.=$n2$n1=$n1.$n2

Comparision Operators

  • As the name implies, comparison operators allow you to compare two values.
  • Let us check every operator with example.
OperationExampleResult
Equal$no1==$no2True, if $no1 and $no2 have same value
Identical$no1===$no2True, if and only if $no1 and $no2 have same value and data type as well
Not Equal$no1!=$no2True, if $no1 and $no2 have not same value
Not Equal$no1<>$no2True, if $no1 and $no2 have not same value
Not Identical$no1!==$no2True, if $no1 and $no2 have not same value or they don’t have same data type
Less than$no1<$no2True, if $no1 is less than $no2
Greater than$no1>$no2True, if $no1 is greater than $no2
Less than or equal to$no1<=$no2True, if $no1 is less than or equal to $no2
Greater than or equal to$no1>=$no2True, if $no1 is greater than or equal to $no2

Incrementing/Decrementing Operators

  • PHP supports C style post increment/decrement and pre increment/decrement operators.
OperationExampleResult
Pre Increment++$no1Increments $no1 by one, then returns $no1
Post Increment$no1++Returns $no1, then increments $no1 by one
Pre Decrement–$no1Decrements $no1 by one, then returns $no1
Post Decrement$no1–Returns $no1, then decrements $no1 by one
  • Now let us check out every operator with example below
<?php
	$a = 10;
	echo "Post incrementing(10) = ".$a++."<br>";
	echo "Now the value is = ".$a."<hr>";

	$b = 10;
	echo "Pre incrementing(10) = ".++$b."<br>";
	echo "Now the value is = ".$b."<hr>";
		
	$c = 10;
	echo "Post decrementing(10): ".$c--."<br>";
	echo "Now the value is = ".$c."<hr>";

	$d = 10;
	echo "Pre decrementing(10) ".--$d."<br>";
	echo "Now the value is = ".$d;
?>
Output
Post incrementing(10) = 10
Now the value is = 11

----------------------------------
Preincrementing(10) = 11
Now the value is = 11
----------------------------------
Post decrementing(10): 10
Now the value is = 9
----------------------------------
Pre decrementing(10) 9
Now the value is = 9

Logical Operators

OperationExampleResult
And$a and $bTrue, if both $a & $b are true
And$a && $bTrue, if both $a & $b are true
Or$a or $bTrue, if either $a or $b is true
Or$a || $bTrue, if either $a or $b is true
Not! $a True, if $a is not true

String Operators

  • In PHP, there are two string operators – (.) that returns the concatenation of its right and left arguments and (.=) that appends the argument on the right side to the argument on the left side.
  • Example
<?php
        $v1 = "Good ";
	$v2 = $v1 . "Morning!"; 
        // now $v2 contains "Good Morning!"
	echo $v2."<hr>";
	
	$v3 = "Hey! ";
	$v3 .= "How's the day!";     
       // now $v3 contains "Hey! Hows the day!"
	echo $v3."<hr>";
?>
Output
Good Morning!
------------------------------------------
Hey How's the day!

For more practical information, See https://swatilathia.com/php-video-tutorial/#PHP_Operators_Arithmetic_Operators

User Defined Function (UDF)

  • UDF is a function that is defined by the user to execute his/her own code of programme or according to his/her requirement.
  • UDF is useful when we need one block of code to execute more than once in one page at a different place.
  • Once you create a UDF error free, you can use it as many times as you want without writing it again.
  • Simple, you just need to call it with its name.
  • UDF is a block of code written by the user in following format:

Structure of UDF

<?php
      function func_name(arg1, arg2,..)
      {
          body of the function
      }
      //to call the UDF, use name of the function with parentheses
      func_name();
?>
  • Name of the function starts with a letter or underscore, followed by any number of letters, numbers, or underscores. 

Example 1 : UDF without arguments

In this example, we are using variables ($a and $b) inside the function which gives the total of the two.

  • These variables are known as local variables, which we will discuss later on.
//UDF without arguments
function add()
{
	$a=10;
	$b=30;
	echo "Total of a & b = ".($a+$b);
}
//call UDF
add();

Output
Total of a & b = 40

Example 2 : UDF with arguments (Call by Value)

  • In this example, we are using two parameters/ arguments inside the parentheses $a and $b. When we call the function, we must pass the values for these two variables respectively.
  • So, when we pass 30 and 50, 30 will be assigned to $a and 50 will be assigned to $b and then we get the total of the two.
<?php
	//UDF with arguments or call by values
	function add($a,$b)
	{
		echo "Total of a & b = ".($a+$b);
	}
	//call UDF with passing values
	add(30,50);
?>

Output
Total of a & b = 80

Example 3 : Default argument function

  • In this type of function, we can provide value with argument to make it default.
<?php
	//Default argument function
	//Always write non-default argument at the beginning 
	function add($s1,$s2="World")
	{
		echo $s1." ".$s2;
	}
	/* We only pass the value for argument $s1,
	as $s2 is default argument*/
	add("Hello");
?>

Output
Hello World
  • If we pass the value for $s2 (default argument), that new value will override the default value. Look at the example below:
<?php
	//Default argument function
	//Always write non-default argument at the beginning 
	function add($s1,$s2="World")
	{
		echo $s1." ".$s2;
	}
	//We pass the value for argument $s1,$s2 both
	add("Hello","Swati");
?>
Output 
Hello Swati

Example 4 : Return function

  • A UDF can return a value of any data type just using return statement inside the body of the function.
  • A return statement ends the execution of a function, and returns control to the calling function.
  • A return is used to send a value back to where’s it’s called from.
<?php
	//return function
	function cube($a)
	{
		return ($a*$a*$a);
	}
	//to print the value which return, use echo
	echo "The Cube of 9 = ".cube(9);
?>

 Example 5 : Variable function

  • If a variable name has parentheses appended to it, PHP will look for a function with the same name as whatever the variable evaluates to, and will attempt to execute it. 
<?php
	//variable function
	function demo()
	{
		echo "Hi i am a variable function";
	}
	/* variable $var has a value 'demo' 
	which is same as function name
	declared earlier */
	$var='demo';
	$var();
?>

Output
Hi i am a variable function

For more practical information, see https://swatilathia.com/php-video-tutorial/#PHP_UDF_%E2%80%93_Argument_Function_and_Default_argument_function

https://swatilathia.com/php-video-tutorial/#PHP_Variable_as_function_Return_function_Variable_Length_Argument_Functions

Scope of a Variable

  • A variable’s scope is the context where it has been defined.
  • It is known as the lifetime of a variable or portion of the program within which it can be accessed.
  • In PHP, there is three different variable scopes: local, global and static

Example 1 : Local Scope and Global Scope

<?php
	$a=100;//global scope
	function demo()
	{
		$a=10;//local scope
		echo "The value of a inside UDF = ".$a."<br>";
	}
	demo();
	echo "The value of a outside UDF = ".$a."<br>";
?>
Output
The value of a inside UDF = 10
The value of a outside UDF = 100
  • Any variable used inside UDF is by default local to that function.
  • Outside UDF variable ‘a’ does not access as 10 because it loses its value.
  • But we have already declared a = 100 outside UDF, which can access outside the UDF.
  • So in the above example, when we call UDF, it prints the value of a = 10 as local scope
  • Now when we print the value of ‘a’ outside the UDF, it prints a = 100 as we declare variable a = 100 which represents global scope.

Example 2 : Using global keyword

<?php
	$a=100;//global scope
        $b=200;//global scope
	function demo()
	{
		//global scope
		global $a, $b;
		echo "The value of a inside UDF = ".$a."<br>";
		echo "The value of b inside UDF = ".$b."<br>";
	}
	demo();
?>

Output
The value of a inside UDF = 100
The value of b outside UDF = 200
  • If you want to use the value of global variables inside UDF, you just need to write global keyword before declaring same variable name inside UDF.
  • In above example, we declare two variables : a & b outside the UDF and can access inside UDF using “global” keyword.
  • If you change anything in global variable inside UDF, that change reflects throughout the script.
<?php
	$a=100;//global scope
	$b=200;//global scope
	function demo()
	{
		//global scope
		global $a, $b;
		echo "The value of a inside UDF = ".$a."<br>";
		echo "The value of b inside UDF = ".$b."<br>";
		$a=$a+$b;
	}
	demo();
	echo "Now the value of a = ".$a."<br>";
?>

Output
The value of a inside UDF = 100
The value of b inside UDF = 200
Now the value of a = 300

Example 3 : Using $GLOBALS

  • We can use $GLOBALS to access value of global variable inside UDF.
  • $GLOBALS is an associative array with the name of variable, which is global or super global variable.
<?php
$a=100;//global scope
$b=200;//global scope
function demo()
{
echo "The value of a inside UDF = ".$GLOBALS['a']."<br>";
echo "The value of b inside UDF = ".$GLOBALS['b']."<br>";
}
demo();
?>

Output
The value of a inside UDF = 100
The value of b inside UDF = 200

Example 4 : Static Scope

  • Let us look at the example below
<?php
	function demo()
	{
		$a=10;//local scope
		echo $a."<br>";
		$a++;
	}
	demo();
	demo();
	demo();
?>

Output
10
10
10
  • We actually wanted to get 1, 2, 3 as we have called demo() three times. But according to local scope of a variable, when the variable leaves the UDF, it loses its value which is being incremented from 1 to 2.
  • When we call demo() again, it prints 1 again and not 2. Likewise, third time when we call demo(), it prints 1 again and not 3.
  • The solution of this type of problem is Static variable.
  • To make the variable static, just write ‘static’ keyword before using variable name.
  • Static variable does not lose its value when it leaves the UDF and it preserves what it has.
  • Look at the example below.
<?php
	function demo()
	{
		Static $a = 10;//static scope
		echo $a."<br>";
		$a++;
	}
	demo();
	demo();
	demo();
?>

Output
10
11
12

Conditional Structure

  • Simple If, If…else, If…elseif…else and switch case are all included in Conditional structure of PHP.

Structure of If statement

  • The statement between curly braces executed if the condition is true.
  • If the condition will be false, it will be ignored.
<?php
	if(condition)
	{
		statement to be executed
	}
?>

Example 1 : If statement

  • In this example, we have taken the value of a = 5 which less than 10 according to the given condition. So the given condition is being true and the statement between the curly brackets will be executed.
<?php
	$a = 5;
	if($a < 10)
	{
		echo "a is less than 10";
	}
?>

Output
a is less than 10

Structure of If … else statement

  • The statement between curly braces executed if the condition is true.
  • If the condition is false, the statement inside else part will be executed.
<?php
	if(condition)
	{
		statement to be executed
	}
	else
	{
		other statement to be executed
	}
?>

Example 2 : If … else statement

  • Here we have two variables a=5 and b=10. According to the condition, a is less than b, so the statement inside If will be displayed. Hence, the given If condition is true.
<?php
	$a = 5;
	$b = 10;
	if ($a < $b)
	{
		echo "a is less than b";
	}
	else
	{
		echo "a is not less than b";
	}
?>

Output
a is less than b

Structure of If … elseif … else statement

  • If there are more than one conditions to be checked, you can use if … elseif … else statements.
  • In this statement, if condition is not true, PHP will check for next the condition inside elseif.
  • If elseif condition is not true, PHP will go for the else part and execute the statement inside else.
  • You can put as many elseif as you want.
<?php
	if (condition)
	{
		statement to be executed
	}
	elseif (condition)
	{
		statement to be executed
	}
	elseif (condition)
	{
		statement to be executed
	}
	else
	{
		statement to be executed
	}
?>

Example 3 : If … elseif … else statement

<?php
	$a = 10;
	$b = 10;
	if ($a < $b)
	{
		echo "a is less than b";
	}
	elseif ($a > $b)
	{
		echo "a is greater than b";
	}
	else
	{
		echo "a and b are equal";
	}
?>

Output
a and b are equal

Structure of Switch case statement

  • The Switch statement is similar to a collection of If statements on the same expression.
  • In some cases, you may want to compare the same variable (or expression) with many different values and execute a different piece of code depending on which value it equals to.
  • This is what Switch statement does.
<?php
switch(variable/expression) 
{
    case 1:
		statement to be executed
		break;
    case 2:
		statement to be executed
		break;
    case 3:
		statement to be executed
		break;
    default:
		statement to be executed
}
?>

Example 4 : Switch case statement

  • In this example, the value of $day will be compared with every case. If any case matches with the value of $day, the statement of the corresponding case will be executed.
<?php
    $day="Thursday";
    switch($day) 
    {
    case "Monday":
			echo "It's Monday";
			break;
    case "Tuesday":
			echo "It's Tuesday";
			break;
    case "Wednesday":
			echo "It's Wednesday";
			break;
    case "Thursday":
			echo "It's Thursday";
			break;
    case "Friday":
			echo "It's Friday";
			break;
    case "Saturday":
			echo "It's Saturday";
			break;
    default:
			echo "Hey It's Sunday";
}
?>

Looping Structure

  • PHP has mainly four types of looping structure : While, Do … while, for and foreach.

Structure of While loop

  • PHP executes the statement(s) repeatedly, as long as the while expression evaluates to true.
  • The value of the expression is checked every time at the beginning of the loop, so even if this value changes during the execution of the statement(s), execution will not stop until the end of the loop.
  • If the while expression evaluates to false from the beginning, the statement(s) will not even be executed once.
  • While loop is also known as entry control loop as it checks every value/ expression before entering into the while loop.
While(expression)
{
      Statement(s) to be executed
}

Example 1 : While loop

<?php 
$a=1; 
while($a<=5) 
{ 
       echo "The value of a = ".$a."<br>"; 
       $a++; 
} 
?>

Output
The value of a = 1
The value of a = 2
The value of a = 3
The value of a = 4
The value of a = 5

Structure of Do … while loop

  • Do.. while loop does the same job as while excepts it doesn’t check the expression at the beginning of the loop. When first iteration completes, it checks for the expression at the end of the loop.
  • That means by default do… while loop iterates one time and executes whatever inside the loop at least once.
  • If the expression evaluates wrong, it will not iterate further.
  • Do…while loop is also known as exit control loop.
<?php
      do{
	        statement(s) to be executed
	}while(expression);
?>

Example 2 : Do … while loop

<?php
	$a=1;
	do{
		echo "The value of a = ".$a."<br>";
		$a++;
	}while($a<=5);
?>

Output
The value of a = 1
The value of a = 2
The value of a = 3
The value of a = 4
The value of a = 5
  • In below example, the expression is not satisfied according to the value of $a, still it prints the value of a=10. Then it will stop iterating as it will check the expression at the end of the loop.
<?php
	$a=10;
	do{
		echo "The value of a = ".$a."<br>";
		$a++;
	}while($a<=5);
?>

Output
The value of a = 10

Structure of for loop

Scroll to top