You are on page 1of 47

Basic php notes

PHP Introduction
 PHP is a server side programming language that is mostly used for web applications.
 There are many advantages of choosing PHP language over others. In this PHP Tutorial, you
will learn more about PHP Usage, Feature, History, and Future scope.
 Uses of PHP:
 Using PHP, you can create static as well as dynamic websites. Here are some of the common
uses of PHP programming.
 PHP is able to perform various arithmetic and logical operations on the given data.
 PHP can store and retrieve data from the database.
 You can create dynamic functionality on any website using PHP. A few examples are Login,
Registration, Gallery, Survey, Forums and many more.
 PHP can transfer data among different web pages in a website.
Features of php
 PHP is easy to learn for beginners.
 PHP Language runs on almost all operating systems. For example Windows, Linux, Unix, Mac
OS X.
 PHP is compatible with various web servers. For example Apache, IIS, etc
 PHP supports a wide range of database management systems like MySQL, PostgreSQL,
Oracle, MS SQL.
 PHP is open-source and free.
PHP Facts
 The full form of PHP is “PHP: Hypertext Preprocessor”
 Initially, the PHP term stood for Personal Home Page.
 Rasmus Lerdorf has developed PHP language initially in 1995.
 PHP is used as a procedural programming as well as object-oriented
programming.
 Some of the biggest online brands use PHP in some form or
functionality. Some examples are: Facebook, WhatsApp, Wikipedia,
Flickr, jQuery Blog, and WordPress are powered by PHP.
 Why PHP is widely used programming language in the world?
 As PHP is open-source, it becomes affordable to purchase web hosting for PHP website. Also, PHP
web development cost is low as compared to many other languages.
 PHP language is easy to set up in different environments using software like XAMPP, WAMP, LAMP.
 PHP programming syntax is easy to learn and understand.
 There is huge support available on the internet for PHP to find solutions for any problem. There are
more than 100000 PHP questions has been answered on StackOverFlow
 You can find many PHP scripts online for your projects or websites.
 Example of a Simple PHP program:
 As of now, you have a basic idea about the PHP Programming Language. We will now have a
look at a simple PHP program.

 <?php
 echo "Hello, This is a simple PHP program!";
 ?>
 PHP
 This program consists of PHP opening & closing bracket. You need to write PHP code within
these brackets. Then, we have used a simple “echo” statement to display a simple message on the
browser screen.
PHP TERMINOLOGIES
 How to set up PHP on Your Own PC:
 install a web server
 install PHP
 install a database, such as MySQL
 Instead of installing each software individually, we can use the combined environment
package. There are various development environments available that can install Web-
server/PHP/MySQL easily at once.
 XAMPP is the most popular PHP development environment. XAMPP is a completely
free, easy to install Apache distribution containing PHP, MySQL and Perl. The XAMPP
open source package has been set up to be incredibly easy to install and to use.
Basic PHP Syntax

 A PHP script or code starts with <?php and ends with ?>
 The default file extension for PHP files is “.php”. For example: file1.php
 A PHP file normally contains some PHP statements, variables, functions and some HTML
tags as well.
 Let us start with a simple PHP script. We will create a program to print “Hello World!”
using the PHP function echo.

 <?php
 echo "Hello World!";
 ?>
How to run PHP Program:

 If you have installed XAMPP, all of your PHP code files will be placed in “htdocs” folder.
The full path of htdocs folder will be something like D:\xampp\htdocs.
 Open notepad and create a simple program. You can copy the above example as well.
 Then save your file with PHP extension such as sample.php. You need to place or Save
your ‘sample.php’ file in htdocs folder.
 Now you can open any web browser such as chrome and run your PHP file using the
localhost URL.
 For example, if your file is located: ‘D:\xampp\htdocs\sample.php’, You need to type in
browser URL: ‘http://localhost/sample.php’ and hit enter. You PHP program will run and
give output such as ‘Hello World’
PHP Comments

 PHP Comments is one of the most important parts of the code. By using comments, the developer can easily understand the code. These comments are simply a
description of the PHP script or code. PHP comments don’t affect the code.
 In HTML, we see there is only one type of comment. While PHP has two types of comments i.e.

 Single Line Comment


 Multiple Line Comment
 Single line comment
 The Single-line comments are used to tell the developer to ignore everything which comes to the right side of that syntax of single-line comment.
 We can use single-line comments by the following two ways:

 //
 #
 There is no need to end the single-line comment.

 <?php
 echo "Hello World!"; // This is single line comment
 #This is also a single line comment
 ?>
Multiple line comment

 The Multiple PHP comment can be used to comment out large blocks of code(we can even
comment paragraphs in PHP script).
 The multiple line PHP comment begins with /* and ends with */.We must end the multiple
line comment.

 <?php
 /* This is a multiple line comment
 here we print Hello World statement */
 echo "Hello World!";
 ?>
PHP Variables

 A PHP Variable is simply an element or data item that may take on more than one value during the
run-time of a program.

 In other words, a PHP variable store a value that can change, depending on conditions or on
information passed to the program.
 PHP Variables Rules:
 In PHP, variable names are case-sensitive.
 Variables in PHP are represented by a dollar sign followed by the name of the variable.
 A valid variable name starts with a letter or underscores, followed by any number of letters,
numbers, or underscores.
 After declaring a variable it can be reused throughout the code.
 A variable does not need to be declared before adding a value to it.
 PHP automatically converts the variable to the correct data type, depending on its value.
 The assignment operator (=) used to assign value to a variable.
 PHP Variables Example:
 <?php
 $content = "Hello PHP!";
 $a = 10;
 $_msg = 'Hello again';

 echo $content;
 echo "<br>".$a;
 echo "<br>".$_msg;
 ?>
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 Operators with Example

 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 (Introduced in PHP 5.6)
 <?php
 $x = 8;
 $y = 2;

 echo $x + $y."\n";
 echo $x - $y."\n";
 echo $x * $y."\n";
 echo $x / $y."\n";
 echo $x % $y."\n";
 echo $x ** $y."\n";
 ?>
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 The left operand gets set to the value of the expression on the right
 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
Comparison Operators

 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
 === Identical $x === $y Returns true if $x is equal to $y, and they are of the 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 $x !== $y Returns true if $x is not equal to $y, or they are not of 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 equal to $x >= $y Returns true if $x is greater than or equal to $y
 <= Less than or equal to $x <= $y Returns true if $x is less than or equal to $y
Increment / Decrement Operators

 The PHP decrement operators are used to decrement a variable’s value.

 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
Logical Operators

 The PHP logical operators are used to combine conditional statements.

 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
String Operators

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

 Operator Name Example Result


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

 The PHP array operators are used to compare arrays.

 Operator Name Example Result


 + Union $x + $y Union of $x and $y
 == Equality $x == $y Returns true if $x and $y have the same key/value pairs
 === Identity $x === $y Returns true if $x and $y have the same 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-identity $x !== $y Returns true if $x is not identical to $y
PHP String:

 A string is a sequence of characters enclosed inside quotes.


 $name = "Robin Kumar";
 echo $website;
 PHP
 Generally, we use string to store names, description, and many more things. In this
example, we have assigned a person name to variable $name.
PHP Integer

 Integers are whole numbers that can be used to assign person age, count, calculations
and many purposes.
 Numbers can be positive and negative.
 Numbers can not be without fractional part i.e they cannot be decimal numbers.
 The range of an integer or numbers can be between 2,147,483,648 and 2,147,483,647
i.e., -2^31 to 2^31.
 PHP Float Data Type
 Floating-point numbers represent real numbers in computing. Real numbers measure
continuous quantities, like weight, height, or speed. Floating-point numbers in PHP can
be larger than integers and they can have a decimal point.
 <?php
 $s = "this is string example"; // $s is a string variable
 echo $s."<br>";
 $i = 10; // $i is an integer variable
 echo $i."<br>";
 $f = 1.3; // $f is now a float (3.3)
 echo $f."<br>";
 $concat_i = $i."10 Little Piggies"; // integer
 echo $concat_i."<br>";
 ?>
PHP Decision Making

 PHP Decision Making Statements


 PHP decision statements are used to make a decision, based on some conditions.

 Type of Decision-Making Statements:


 Here are different types of Decision Making Statements in PHP.

 The if…else statement


 The elseif statement
 The switch…case statement
 The if….else statement
 The if statement is used to execute a block of code only if the specified
condition is true.

 Syntax
 if (condition)
 code to be executed if condition is true;
 else
 code to be executed if condition is false;
 <?php
 $day = "Friday";

 if ($day == "Friday") {
 echo “Hoza weekend";
 } else {
 echo "its not Friday";
 }
 ?>
 The elseif Statements
 If you want to execute some code if one of the several conditions are true use the elseif statement.

 Syntax
 if (condition)
 code to be executed if condition is true;
 elseif (condition)
 code to be executed if condition is true;
 else
 code to be executed if condition is false;
 <?php
 $day = "Sunday";

 if ($day == "Friday") {
 echo "its friday";
 }
 else if ($day == "Sunday") {
 echo "its weekend";
 } else {
 echo "its not weekend as well not Friday";
 }
 ?>
Switch statement
 The switch…case statement
 The switch statement is used to perform different actions based on different conditions.
Syntax
 switch(n){
 case label1:
 // Code to be executed if n=label1
 break;
 case label2:
 // Code to be executed if n=label2
 break;
 ...
 default:
 // Code to be executed if n is different from all labels
 }
 <?php
 $fav_fruit = "mango";

 switch ($fav_fruit) {
 case "orange":
 echo "Your favorite fruit is orange!";
 break;
 case "mango":
 echo "Your favorite fruit is mango!";
 break;
 case "apple":
 echo "Your favorite fruit is apple!";
 break;
 default:
 echo "Your favorite fruit is neither orange, mango, nor apple!";
 }
 ?>
Assignment
1. Write a basic calculator program in PHP using switch case
You need to write a simple calculator program in PHP using switch case.
Operations:
Addition
Subtraction
Multiplication
Division
Modulus
Power
PHP Loops

 PHP Loops are used to execute the same block of code again and again until a certain condition is
met.
 Types of Loops
 for loop − loops through a block of code a specified number of times.
 while — loops through a block of code until the condition is evaluated to true.
 do…while — the block of code executed once and then condition is evaluated. If the condition is
true the statement is repeated as long as the specified condition is true.
 foreach − loops through a block of code for each element in an array.
for Loop

 The for loop repeats a block of code until a certain condition is met. It is typically used
to execute a block of code for certain number of times.
 The for loop is used when you know in advance how many times the script should run.
 Syntax
 for(initialization; condition; increment){
 #code to be executed
 }
 Parameters of for loop :
Initialization :is used to set a counter.
Condition : if condition is true loop will continue, if the condition is false loop ends.
Increment : used to increment the counter.
Eg i (print the statement 5 times)// Code to be executed
For loop

 <?php
 for($i=1; $i<=5; $i++){
 echo $i."\n";
 }
 ?>
Practical questions

 Find the Sum of even and odd numbers between 1 to 100.


 Find all odd numbers between 1 to 100 using loop
 Find all even numbers between 1 to 100
while Loop

 The while loop executes a block of code as long as the specified condition is true.

 Syntax
 while (condition is true) {
 code to be executed;
 }
 <?php
 $n = 1;
 while($n <= 5) {
 echo "The number is: $n \n";
 $n++;
 }
 ?>
do…while Loop

 The do…while statement will execute a block of code at least once – it then will repeat
the loop as long as a condition is true.
 Syntax
 do {
 code to be executed;
 }
 while (condition);

<?php
$n = 6;

do {
echo "The number is: $n \n";
$n++;
} while ($n <= 5);
?>
foreach Loop

 The foreach statement is used to loop through arrays. For each pass the value of the current array element is
assigned to $value and the array pointer is moved by one and in the next pass next element will be processed.
 Syntax
 foreach (array as value)
 {
 code to be executed;
 }
 <?php
 $fruits = array("mango", "apple", "papaya", "lichi");
 foreach ($fruits as $value)
 {
 echo "$value \n";
 }
 ?>
PHP ARRAYS
 PHP array is a linear data structure that can store more than one values under a single variable.

 Types of Arrays
 There are three different kind of arrays and each array value is accessed using an ID, which is
called array index.

 Numeric/Indexed Array − An array with a numeric index. Values are stored and accessed in linear
fashion.
 Associative array − An array with strings as an index. This stores element values in association
with key values rather than in a strict linear index order.
 Multidimensional array − An array containing one or more arrays and values are accessed using
multiple indices.
Numeric/Indexed Array
.

 An indexed or numeric array stores each array element with a numeric index

 <?php
 $fruit = array("Mango", "Papaya", "Orange");
 echo "I would like to eat " . $fruit[0] . ", " . $fruit[1] . " and " . $fruit[2] . ".";
 ?>
Associative Arrays

 The associative arrays are very similar to numeric arrays in term of functionality but they are
different in terms of their index. Associative array will have their index as string so that you can
establish a strong association between key and values.

 <?php $age = array("Symntha"=>"15", "Clan"=>"17", "Smith"=>"23");


 echo "Symntha is " . $age['Symntha'] . " years old."; ?>
Multi-dimensional Array

 A multi-dimensional array each element in the main array can also be an array. And each element in the sub-array
can be an array, and so on. Values in the multi-dimensional array are accessed using multiple index.

 <?php
 $cars = array
 (
 array("Elentra",22,18),
 array("Audi",15,13),
 );
 echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".\n";
 echo "<br>";
 echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".\n";
 ?>
result

 Elentra: In stock: 22, sold: 18.


 Audi: In stock: 15, sold: 13.

You might also like