LAB C1 Introduction To PHP
LAB C1 Introduction To PHP
1.0) Introduction
PHP is an open-source, interpreted, and object-oriented scripting language that can be
executed at the server-side. The goal of the language is to allow web developers to write
dynamically generated pages quickly. PHP runs on different platforms (Windows, Linux,
Unix, etc.). PHP is compatible with almost all servers used today. PHP is FREE to
download from the official PHP resource: www.php.net. The fundamental characteristics
of PHP are:
<?php
//your code here
?>
1.5) How to create and run a PHP file using WAPM or XAMPP.
The functional steps involved in creating and running a PHP program are as follows:
Step 1: Open a text editor (such as notepad) and create a simple PHP code.
<?php echo "Hello PHP Web Engineers!"; ?>
Step 2: Go to save as at file menu and save the file giving three parameters:
i) select web publishing folder/subfolder (htdocs folder in XAMPP or www
folder in WAMP server at the root).
ii) Give a file name with the extension .php and
iii) select “all types” at the file types.
Step 3: Run the XAMPP server and start the Apache and MySQL from its control panel.
Step 4: Open a browser and type “localhost/your_file_name.php” at the url address bar.
Press enter and you will see the output at the browser “Hello PHP Web
Engineers!”
iii) PHP comments: Single line or multiple line program comments are allowed in PHP
with the following syntax:
a) // this is a single line comment
b) # this is another single line comment
c) /* this is a php multi line comment
this is a php multi line comment
this is a php multi line comment */
iv) The $ symbol: One must prefix the $ symbol before the name of any declared
variable or array (details in next chapter “variable and arrary”).
v) PHP echo and print: PHP echo and print statements are used for display output.
vi) Embedded: PHP code can be easily embedded within HTML tags and script. The
following example will highlight on comments and embedment. Note that, though it is a
html code file saving process must follow 1.5: step 2.
code Result
<html> This is a html code
<head><title>HTML & PHP</title></head> This is a php code
<body>
Hello! I am the output of html code
<BR>
// First five lines are HTML code
<?php
print “Hi, I am PHP output”;
?>
# The red colored lines are PHP code
</body>
</html>
Variables and Data types
What Is a Variable?
A variable is a keyword or phrase that acts as an identifier for a value stored in a system’s
memory. This is useful because it allows us to write programs that will perform a set of actions on
a variable value, which means you can change the output of the program simply by changing the
variable, rather than changing the program itself. In PHP, you define a variable with the following
form: $variable_name = value;
Rules for variables
● The dollar sign ($) must always fill the first space of your variable
● The first character after the dollar sign must be a letter or underscore. It can't under any
circumstances be a number for example, a-z, A-Z, 0-9, and _.;
● Variables in PHP are case sensitive. This means that $variable_name and
$Variable_Name are different.
● Variables with more than one word should be separated with underscores; for example,
$test_variable.
● Variables can be assigned values by using the equals sign (=).
● Always end with a semicolon (;) to complete the assignment of the variable.
Type of Variables
PHP accepts nearly anything in a variable using one of the following data types:
1. String
A string is any series of characters enclosed in single (') or double (") quotes, or that you create
using special heredoc or nowdoc syntax.
a) Single-Quote String: Enclosing a string in single quotes is the simplest way to create a string
in PHP. It doesn’t expand special characters or variables. Ex.
<?php
$abc = 'It\'s cold outside today!';
echo $abc;
?>
b) Double-Quote String: Strings encased in double quotes behave similarly to strings encased in
single quotes but they interpret more special characters, including expanding variables.
<?php
$abc = 'It\'s cold outside today!';
echo $abc;
?>
c) heredoc string: PHP introduces a more robust string creation tool called heredoc that lets the
programmer create multi-line strings without using quotations. It begins with <<< and an
identifier (EOD- End of Document) is used both at the beginning and end of the string that can be
any combination of alphanumeric characters or underscores that don’t begin with a digit.
<?php
$abc = <<<EOD
This is a string created using heredoc syntax.
It can span multiple lines, use "quotes" without
escaping, and it'll allow $variables too.
Special characters are still supported \n as well.
EOD;
echo $abc
?>
d) Nowdoc Syntax Nowdoc syntax is functionally similar to quotes you encase in single
quoted strings, and you call it in much the same way that you call heredoc syntax. The
difference is that you enclose the identifier in single quotes when you open the string:
According to the PHP manual: Nowdocs are to single-quoted strings what heredocs are
to double-quoted strings.
For Example
<?php
$abc = <<<EOD
This is a string created using heredoc syntax.
It can span multiple lines, use "quotes" without
escaping, and it'll allow $variables too.
Special characters are still supported \n as well.;
echo $abc
?>
String Concatenation
It’s often necessary to join two strings together in a script. You accomplish this using the string
concatenation operator, a period (.). One can join two strings together by placing a period
between them while printing or creating a different vcariable:
<?php
$Place= "New York";
$Publisher= "MacGraw Hill";
$Year= "2007";
$imprint = "$Place"." : "."$Publisher".", "."$Year";
Print "$imprint";
?>
2. Integer
An integer is any positive or negative whole number (a number without a decimal value). For example, the
numbers 1, -27, and 4985067 are integers, but 1.2 is not. Because PHP is a loosely typed language, it’s not
necessary to declare a variable as an integer; however, if you find it necessary, you can explicitly cast, or
force, a value as an integer using the following syntax:
$foo = 27; // No quotes around a whole number always means integer
$bar = (int) "3-peat"; // Evaluates to 3
4. Boolean
A Boolean value is the simplest type of data; it represents truth, and can contain only one of two
values: TRUE or FALSE. It’s important to note that the FALSE (not in quotes) Boolean value is
different from the "FALSE" string value, and the same goes for TRUE. Boolean values are not
case sensitive. Booleans are very useful when determining if a condition exists.
5. Array
PHP arrays allow us to store groups of related data in one variable (as opposed to storing them in
separate variables). Arrays are among the most powerful datatypes available in PHP, due to their
ability to map information using a key to value pairing. This means that an array can store
multiple pieces of information in a single variable; all indexed by key. There are 3 different types
of PHP arrays:
i. Numeric arrays
ii. Associative arrays
iii. Multidimensional arrays
i. Numeric array
Numeric arrays use a number as the "key". The key is the unique identifier, or ID, of each item
within the array. The numbering starts at zero for each item of the array either automatically or
manually. Examples are given below:
Constants
Constants are like variables except that, once assigned a value, they cannot be changed. Constants are
created using the define() function and by convention (but not by rule) are in all uppercase letters.
Constants can be accessed from anywhere on the page.
PHP Operator
Like other programming language PHP uses different operators to manipulate or perform operations on
variables and values. These are as follows:
i. Assignment Operators
ii. Arithmetic Operators
iii. Comparison Operators
iv. String Operators
v. Combination Arithmetic & Assignment Operators
vi. Logical Operators
i. Assignment operators
Assignment operators are used to set a variable equal to a value or set a variable to another variable's value.
Such an assignment of value is done with the "=", or equal character. Example:
$my_var = 4;
$another_var = $my_var;
$_a = “hello”;
$_b = “world”;
$_new = $_a . $_b;
?>
Logical Operators
The logical operators test combinations of booleans. The or operator, for example returns true if either the
left or the right operand is true.
&& And Left and right are true true && false False
"--" operator:
To subtract 1 from a variable, or "decrement" use the "--" operator:
$x--; Which is equivalent to $x -= 1; or $x = $x - 1;
Control Structure
To add power and convenience to your scripts, PHP supports a number of conditional statements,
loops, and other control structures that allow us to manipulate data easily throughout your code.
The control structures supported by PHP are as follows and details are discussed later section:
Conditional Statements
1. if statement - use this statement to execute some code only if a specified condition is true
2. if...else statement - use this statement to execute some code if a condition is true and
another code if the condition is false
3. if...elseif....else statement - use this statement to select one of several blocks of code to
be executed
4. switch statement - use this statement to select one of many blocks of code to be executed
Looping
In PHP, we have the following looping statements and they have been discussed in the later
sections:
1. while - loops through a block of code while a specified condition is true
2. do...while - loops through a block of code once, and then repeats the loop as long as a
specified condition is true
3. for - loops through a block of code a specified number of times
4. foreach - loops through a block of code for each element in an array
If statement
Syntax Code and output
if ( expression ) <?Php
{ $number = 100;
code to execute if the expression evaluates to true if($number = = 100)
} {
print “Correct number”;
}
?>
Here we use the comparison operator = = to compare the variable $number with the given number
100. If the assigned variable value and given number match, the expression evaluates to true, and
the code block below the if statement is executed. If you change the value of $number to "50"
and run the script, the expression in the if statement evaluates to false, and the code block is
skipped. The script remains sulkily silent. An alternative to the above if statement may be as
follows:
if ( $number == 100 )
print "Correct number";
ii. else
When working with if statement, we will often want to define an alternative block of code that
should be executed if the expression evaluates to false. We can do this by adding else to the if
statement followed by a further block of code:
else statement
Code Result
if ( expression ) <?Php
{ $number = 100;
code to execute if the expression evaluates to true if ($number == 100)
} {
else print “Correct number”;
{ }
code to execute in all other cases else
} {
print “Wrong number”;
}
?>
output: Wrong number
iii. elseif
we can use an if-elseif-else construct to test multiple expressions before offering a default block
of code: If the first expression does not evaluate to true, then the first block of code is ignored.
The elseif clause then causes another expression to be evaluated. Once again, if this expression
evaluates to true, then the second block of code is executed. Otherwise, the block of code
associated with the else clause is executed. we can include as many elseif clauses as you want,
and if you don't need a default action, you can omit the else clause.
elseif statement
Syntax Code and output
<?Php
if ( expression ) $number = 40;
{ if ($number == 50)
code to execute if the expression evaluates to {
true print 'Correct number';
} }
elseif ( another expression )
{ elseif ($number < 50)
code to execute if the previous expression {
failed and this one evaluates to true print 'It is less then your number';
else }
{
code to execute in all other cases elseif ($number > 50)
} {
print 'It is greater then your number';
}
else
{
print 'Wrong number';
}
?>
ElseIf is a Correct
v. switch
If a multitude of conditions exist, you can use the switch control structure to create different
responses for different conditions—much as you can for an if statement. However, switch works
much better in situations where you have more than one or two conditions. A switch accepts an
expression, then sets up cases. Each case is functionally equivalent to an if statement; this means
that if the expression passed to the switch matches the case, then the code within the case is
executed. You must separate each case with a break statement
switch statement
Syntax Code and output
$Variable with value to check <?php
switch ($variable) $sub = "LIS";
{ echo " If your subject is $sub , ";
case1 ‘value to be evaluated’:
code; switch($sub)
break; {
. case 'sociology':
. echo "Your class number is: 301";
. break;
?> case 'Economics':
echo "Your class number is: 330";
break;
case 'LIS':
echo "Your class number is: 020";
break;
case 'CSE':
echo "Your class number is: 064";
break;
default:
echo "unknown subject";
break;
}
?>
output: If your subject is LIS , Your class
number is: 020
Looping
Loop statements are designed to enable you to achieve repetitive tasks. It decides how many
times to execute a block of code. Almost without exception, a loop continues to operate until a
condition is achieved, or you explicitly choose to exit the loop.
i. While Loop
The meaning of a while statement is simple. It tells PHP to execute the nested statement(s) repeatedly, as
long as the while expression evaluates to TRUE. The value of the expression is checked each time at the
beginning of the loop, so even if this value changes during the execution of the nested statement(s),
execution will not stop until the end of the iteration The syntax is for a while loop is:
Syntax Alternative syntax
while (expression) { while (expression) :
code to execute; } code to execute;
endwhile;
do {
code to execute;
} (expression);
for ( initialize a counter; conditional statement; increment a counter) { php code in the loop }
Note that Each step is separated by a semicolon: initialize counter, conditional statement, and the
counter increment. A semicolon is needed because these are separate expressions. However,
notice that a semicolon is not needed after the "increment counter" expression.
Example of for loop
<?php
/* example 1: Basic */
$i = 1;
for (; ; ) {
if ($i > 10) {
break;
}
echo $i;
$i++;
}
/* example 4 */
This simply gives an easy way to iterate over arrays. foreach works only on arrays, and will issue
an error when you try to use it on a variable with a different data type or an uninitialized variable.
There are two syntaxes; the second is a minor but useful extension of the first.
ii. as $key => $value): does the same thing, except that the current element's
key will be assigned to the variable $key on each loop. The operator "=>"
represents the relationship between a key and value.
Syntax 2 Example
foreach (array_expression as $key => <?php
$value) $x=array(0=>"one",1=>"two",2=>"three");
statement foreach ($x as $key=>$value) {
echo "key = " .$key ." value = ".$value. "<br />"; }
?>
PHP Function
What is function? You can think of a function as a machine. A machine takes the raw
materials you feed it and works with them to achieve a purpose or to produce a product. A
function accepts values from you, processes them, and then performs an action (printing to the
browser, for example) or returns a new value, possibly both. A function, then, is a self-contained
block of code that can be called by your scripts. When called, the function's code is executed. You
can pass values to functions, which they will then work with. When finished, a function can pass
a value back to the calling code.
i. Calling a Function
Functions come in two flavors— those built in to the language and those you define yourself.
PHP4 has hundreds of built-in functions. The very first script in this tutorial consisted of a single
function call. For example, print("Hello Web"). We called the print() function, passing it the
string "Hello Web". The function then went about the business of writing the string. A function
call consists of the function name, print in this case, followed by parentheses. If you want to pass
information to the function, you place it between these parentheses. A piece of information
passed to a function in this way is called an argument. Some functions require that more than one
argument be passed to them. Arguments in these cases must be separated by commas: for
example: some_function( $an_argument, $another_argument ); The abs() function, for example, requires
a signed numeric value and returns the absolute value of that number.
Function calling: Abs function
Code Result
<?php 1200
$_number = -1200;
$new_number = abs($_number);
print $new_number;
?>
PHP Code:
Code Result
<?php The total mark is 75
function tm($a,$b) {
$total = $a + $b;
return $total; }
$totalmarks = “tm”;