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

Chapter Four: PHP Basics

PHP is a server-side scripting language used for web development. It allows developers to manage dynamic content, databases, session tracking, and build entire e-commerce sites. PHP code is embedded into HTML and executed on the server. The key requirements to run PHP include a web server like Apache, a database like MySQL, and a PHP parser. PHP provides many features like performance, open source, platform independence, compatibility, security, and scalability. It supports various data types, variables, control structures, and arrays to manage multiple values in one variable.

Uploaded by

Hussien Mekonnen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
87 views

Chapter Four: PHP Basics

PHP is a server-side scripting language used for web development. It allows developers to manage dynamic content, databases, session tracking, and build entire e-commerce sites. PHP code is embedded into HTML and executed on the server. The key requirements to run PHP include a web server like Apache, a database like MySQL, and a PHP parser. PHP provides many features like performance, open source, platform independence, compatibility, security, and scalability. It supports various data types, variables, control structures, and arrays to manage multiple values in one variable.

Uploaded by

Hussien Mekonnen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 38

Chapter Four

PHP Basics
What is PHP

• Stands for PHP Hypertext Preprocessor


• A server side scripting language that is embedded in HTML
• used to manage dynamic content, databases, session tracking, even
build entire e-commerce sites.
• Integrated with a number of popular databases
• Supports a large number of major protocols that makes n-tier
development a possibility for the first time.
• PHP Syntax is C-Like.
PHP Features
• Performance: Script written in PHP executes much faster than others
• Open Source Software
• Platform Independent: cross platform compatibility
• Compatibility: compatible with almost all local servers
• Embedded:
• Storage & Retrieval: easy storage and retrieval of information from
supported databases.
• Accessibility: reach internet from any device any browser, anytime
• Security: The source code is not exposed & allows encryption
• Scalability: Web-based 3-tier architecture can scale out
Software Requirements

• In order to develop and run PHP Web pages three vital components need

1. Web server like freely available Apache Server


2. Database: work with virtually all database software like MySQL
3. PHP Parser/ Server: to process PHP script instructions and generate HTML
output that can be sent to the Web Browser

• The three software (Apache, PHP, and MySQL) is combine together in Vertigo
or Wamp server.

• For example, we can run Wamp web server in the directory “C:\wamp64\www”.
• Hence, we should save our PHP files in www folder.
Basic PHP syntax
• Four ways to differentiate PHP code from other elements in the page.

1. Canonical PHP tags: 3. ASP style tags


<?php <%
Your PHP code here Your PHP code here
?> %>
2. Short-open tags 4. HTML script tags
<? <script language="PHP">
Your PHP code here Your PHP code here
?> </script>
PHP Comments
• There are two commenting formats in PHP:
1. Single line comment
# This is a comment
// This is a comment too
2. Multiple line comment
/* This is a comment with multiline
Author : Abebe Kebede
Purpose: Multiline Comments Demo
Subject: PHP
*/
PHP Variables
Most important things about PHP variables:
• All variables in PHP are denoted with a leading dollar sign ($).
• The value of a variable is the value of its most recent assignment.
• Variables are assigned with the = operator
• Variables can, but do not need, to be declared before assignment.
• Variables in PHP do not have intrinsic types
• PHP automatically converts the variable to the correct data type,
depending on its value.
• It uses a function var_dump () that print the type and value of variable.
• $x=5.5; var_dump ($x); // return float (5.5);
Variables …
• When creating PHP variables, you must follow similar rules like C++ and Java
• The correct way of declaring a variable in PHP is:
$Variable_Name=value;
• PHP provides a large number of predefined variables to all scripts which are
accessible regardless of scope and you can access them from any function,
class or file without having to do anything special.
• Examples:
• $_SERVER: Server and execution environment information
• $_GET: HTTP GET variables
• $_POST: HTTP POST variables
• And others
PHP Variables Scope

• Scope can be defined as the range of availability or the part of the script where the variable
can be referenced/used.
• PHP variables can be one of three cope types: Local variables, Global variables and Static
variables
• A variable declared in a function is considered local; that is, it can be referenced solely in
that function.
• Any assignment outside of that function will be considered to be an entirely different
variable from the one contained in the function
<?
$x = 4;
function assignx() {
$x = 0; // this is local variable
print "\$x inside function is $x. ";
}
assignx();
print "\$x outside of function is $x. "; • Output:
?> $x inside function is 0.
$x outside of function is 4.
Scope …
• In contrast to local variables, a global variable can be accessed in any part of the program.
• However, in order to be modified, a global variable must be explicitly declared to be global in the
function in which it is to be modified.
<?
$somevar = 15;
function addit() {
GLOBAL $somevar; //use GLOBAL for global variables
$somevar++;
print "Somevar is $somevar";
}
addit();
?>
• This will produce the following result.
Somevar is 16
Scope …
• Normally, when a function is completed/executed, all of its variables are deleted.
• However, sometimes we want a local variable NOT to be deleted if we need it for a
further job. To do this, use the static keyword at the time of declaration
<?php
function myTest() {
static $x = 0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
?>
• This will produce the following result.
012
PHP Output Statement

• As shown above PHP has different syntaxes but for maximum compatibility, it is
recommended to use <?php … ?>
• Each code line in PHP must end with a semicolon which is a separator and is used
to distinguish one set of instructions from another.
• There are two basic statements to output text with PHP: echo and print.
• echo can take multiple parameters (although such usage is rare) but print can
only take one argument.
• echo is marginally faster than print.
• The echo or print statement can be used with or without parentheses: echo or
echo ().
• The general format of the echo statement is as follows:
• echo outputitem1, outputitem2, outputitem3, . . .;
• echo (output statement);
• print (outputstatement);
Datatypes in PHP

• Integers: $int_var = 12345;


• Doubles: $pi= 3.14;
• Boolean: true/false
• Strings
<? php
$variable = "name";
$literally = ' My $variable will not print! ';
print($literally);
$literally = "My $variable will print!\\n";
print($literally);
?>
• This will produce following result:
My $variable will not print!
My name will print
Data types …

• Arrays: are named and indexed collections of other values.

• Objects: are instances of programmer-defined classes

• Resources: are special variables that hold references to resources


external to PHP (such as database connections).
Retrieve data from html forms
• Lets Consider the Following HTML Form Source, form1.html:
<html>
<body>
<form action="get.php" method="GET">
Name: <input type="text" name="name" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>
Form processing …

<?php
if( $_GET["name"] || $_GET["age"] )
{
echo "Welcome ". $_GET['name']. "<br/>";
echo "You are ". $_GET['age']. " years old.";
exit();
}
?>
Form submission with GET
Form submission with POST
Error Reporting
PHP Control Structures

• Control structure allows you to control the flow of code execution in


your application

• PHP supports a number of different control structures:


• Conditional statements like: if, if-else, if-elseif -else and switch statements

• Loop statements like: for, while, do…while ad foreach


If – else statement
<?php
$d = 10;
$c = 20;
if ($c > $d)
{
echo "$c is greater than $d";
}
Else
{
echo "$d is smaller than $c";
}
?>
Switch statement
<?php
$mood = "sad";
switch ($mood)
{
case "happy":
echo "Hooray, I'm in a good mood";
break;
case "sad":
echo "Awww. Don't be down!";
break;
default:
print "Neither happy nor sad but $mood";
break;
}
?>
for loop

loops through a block of code a specified number of times


<?php
$a = 0;
$b = 0;

for( $i=0; $i<5; $i++ )


{
$a += 10;
$b += 5;
}
echo ("At the end of the loop a=$a and b=$b" );
?>
while loop

loops through a block of code if and as long as a specified condition is true.


<?php
$i = 0;
$num = 50;
while( $i < 10)
{
$num--;
$i++;
}
echo ("Loop stopped at i = $i and num = $num" );
?>
do...while
• loops through a block of code once, and then repeats the loop as long as a
special condition is true.
<?php
$i = 0;
$num = 0;
do
{
$i++;
}while( $i < 10 );
echo ("Loop stopped at i = $i" );
?>
foreach
• foreach - loops through a block of code for each element in an array.
• The foreach statement is used to loop through arrays.
• Foreach 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.
• The syntax:
foreach ($arrayname as $keyname => $valuename)
{block of statements; }
foreach …
<?php
$array = array( 1, 2, 3, 4, 5);
foreach( $array as $value )
{
echo "Value is $value <br />";
}
?>
References in PHP

• In PHP, references enable accessing the same variable content by different names
• In PHP, variable name and variable content are different, so the same content can
have different names.
• A reference variable is created by prefixing & sign to original variable.
• Hence $b=&$a will mean that the address of a is assigned to b.
<?php
$var1 =10;
$var2 =&$var1 ;
echo "$var1 $var2\n";
$var2 =20;
echo "$var1 $var2\n";
• Output:
?> 10 10
20 20
PHP Arrays
• A variable is a storage area holding a number or text.
• The problem is, a variable will hold only one value.
• In PHP, the array() function is used to create an array.
• An array is a special variable that stores one or more similar type of
values in a single variable.
• Three kinds of arrays:
• Numeric array - An array with a numeric index.
• Associative array - An array where each ID key is associated with a value
• Multidimensional array - An array containing one or more arrays and values
are accessed using multiple indices
Numeric Array
<?php • Second example for creating arrays
/* First method to create array. */ <?php
/* Second method to create array. */
$numbers = array( 1, 2, 3, 4, 5);
$numbers[0] = "one";
echo "Value of the array:";
$numbers[1] = "two";
foreach( $numbers as $value )
$numbers[2] = "three";
{ $numbers[3] = "four";
echo "$value "; $numbers[4] = "five";
} echo "Value of the array:";
?> foreach( $numbers as $value )
{
echo "$value ";
}
?>
Associative Arrays

• The associative arrays are very similar to numeric arrays in terms of


functionality but they are different in terms of their index.
• When storing data about specific named values, a numerical array is
not always the best way to do it.
• Associative array will have their index as string so that you can
establish a strong association between key and values.
• Example:
• In this example we use an array to assign credit_hours to the different courses:
$credit_hour = array("AIP"=>3, "AP"=>3, "DCN"=>4, "CMT"=>4, "EDP"=>4);
Multi-dimensional array
• In 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 indexes.
• Example:
<?php
$grade =
array("Elias"=>array("AIP"=>'A',"AP"=>'B'),"Ermias"=>array("AIP"=>'B',
"AP"=>'C'));
foreach($grade['Elias'] as $key=>$value)
echo "<br>Elias scored:".$value." in ".$key;
foreach($grade['Ermias'] as $key=>$value)
echo "<br>Ermias scored:".$value." in ".$key;
?>
Adding and Removing Array Elements
Sorting Arrays
• PHP comes with a number of built-in functions designed for sorting
array elements in different ways.
• The first of these is the sort() function, which lets to sort numerically
indexed arrays alphabetically or numerically, from lowest to highest
value.
• Some Sorting Functions of PHP which has different sorting orders
are:-
• sort() : sorts the elements in the numeric and alphabetical order.
• rsort() : sorts the elements in the reverse order.
• asort() : sorts the elements in the array without changing the indices.
• ksort() : sorts the arrays by key.
PHP functions

• PHP functions are similar to functions in other programming languages.


• A function is a piece of code which takes one or more input in the form of
parameter and does some processing and returns a value.
• To use PHP user defined functions, there are two steps:
• Creating a PHP Function
• Calling a PHP Function
PHP functions with parameters
Passing Arguments by Reference
Returning by Reference

You might also like