0% found this document useful (0 votes)
6 views33 pages

Unit-2 PHP

This document provides an overview of programming with PHP, focusing on conditional statements, looping statements, and arrays. It explains various types of conditional statements such as if, if-else, if-elseif-else, and switch, along with examples. Additionally, it covers looping constructs like while, do...while, and for statements, as well as the concept of arrays in PHP, including indexed, associative, and multidimensional arrays.

Uploaded by

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

Unit-2 PHP

This document provides an overview of programming with PHP, focusing on conditional statements, looping statements, and arrays. It explains various types of conditional statements such as if, if-else, if-elseif-else, and switch, along with examples. Additionally, it covers looping constructs like while, do...while, and for statements, as well as the concept of arrays in PHP, including indexed, associative, and multidimensional arrays.

Uploaded by

tasleembanu907
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Unit-2 PROGRAMMING WITH PHP

Conditional Statements:
Conditional Statements are used to perform actions based on different
conditions. Sometimes when we write a program, we want to perform some
different actions for different actions. We can solve this by using conditional
statements.
In PHP we have these conditional statements:

1. if Statement.
2. if-else Statement
3. If-elseif-else Statement
4. Switch statement

If Statement: PHP if statement allows conditional execution of code. It is


executed if condition is true.

If statement is used to executes the block of code exist inside the if statement
only if the specified condition is true.

Syntax
if(condition){
//code to be executed
}

Example
<?php
$num=12;
if($num<100){
echo "$num is less than 100";
}
?>

Output:
12 is less than 100

If-else Statement

PHP if-else statement is executed whether condition is true or false.

If-else statement is slightly different from if statement. It executes one block of


code if the specified condition is true and another block of code if the condition
is false.

Syntax
if(condition){
//code to be executed if true
}else{
//code to be executed if false
}

Example
<?php
$num=12;
if($num%2==0){
echo "$num is even number";
}else{
echo "$num is odd number";
}
?>

Output:
12 is even number

PHP If-else-if Statement

The PHP if-else-if is a special statement used to combine multiple if?.else


statements. So, we can check multiple conditions using this statement.

Syntax
if (condition1){
//code to be executed if condition1 is true
} elseif (condition2){
//code to be executed if condition2 is true
} elseif (condition3){
//code to be executed if condition3 is true
....
} else{
//code to be executed if all given conditions are false
}

Example
<?php
$marks=69;
if ($marks<33){
echo "fail";
}
else if ($marks>=34 && $marks<50) {
echo "D grade";
}
else if ($marks>=50 && $marks<65) {
echo "C grade";
}
else if ($marks>=65 && $marks<80) {
echo "B grade";
}
else if ($marks>=80 && $marks<90) {
echo "A grade";
}
else if ($marks>=90 && $marks<100) {
echo "A+ grade";
}
else {
echo "Invalid input";
}
?>

Output:
B Grade

PHP nested if Statement

The nested if statement contains the if block inside another if block. The inner if
statement executes only when specified condition in outer if statement is true.

Syntax

if (condition) {
//code to be executed if condition is true
if (condition) {
//code to be executed if condition is true
}
}

Example

<?php
$age = 23;
$nationality = "Indian";
//applying conditions on nationality and age
if ($nationality == "Indian")
{
if ($age >= 18) {
echo "Eligible to give vote";
}
else {
echo "Not eligible to give vote";
}
}
?>

Output:

Eligible to give vote

PHP Switch

PHP switch statement is used to execute one statement from multiple


conditions. It works like PHP if-else-if statement.

Syntax
switch(expression){
case value1:
//code to be executed
break;
case value2:
//code to be executed
break;
......
default:
code to be executed if all cases are not matched;
}
Important points to be noticed about switch case:
1. The default is an optional statement. Even it is not important, that default
must always be the last statement.
2. There can be only one default in a switch statement. More than one
default may lead to a Fatal error.
3. Each case can have a break statement, which is used to terminate the
sequence of statement.
4. The break statement is optional to use in switch. If break is not used, all
the statements will execute after finding matched case value.
5. PHP allows you to use number, character, string, as well as functions in
switch expression.
6. Nesting of switch statements is allowed, but it makes the program more
complex and less readable.
7. You can use semicolon (;) instead of colon (:). It will not generate any
error.
Program to check Vowel and consonant

We will pass a character in switch expression to check whether it is vowel or


constant. If the passed character is A, E, I, O, or U, it will be vowel otherwise
consonant.

<?php
$ch = 'U';
switch ($ch)
{
case 'a':
echo "Given character is vowel";
break;
case 'e':
echo "Given character is vowel";
break;
case 'i':
echo "Given character is vowel";
break;
case 'o':
echo "Given character is vowel";
break;
case 'u':
echo "Given character is vowel";
break;
case 'A':
echo "Given character is vowel";
break;
case 'E':
echo "Given character is vowel";
break;
case 'I':
echo "Given character is vowel";
break;
case 'O':
echo "Given character is vowel";
break;
case 'U':
echo "Given character is vowel";
break;
default:
echo "Given character is consonant";
break;
}
?>

Output:

Given character is vowel

Using the ?: (Ternary) Operator


The ?: or ternary operator, it returns a value derived from one of two
expressions separated by a colon. It has three parts, hence the name ternary.

(expression) ? returned_if_expression_is_true : returned_if_expression_is_false;

If the test expression evaluates to true, the result of the second expression is
returned; otherwise, the value of the third expression is returned.
Example1:
<?php
$a = 10;
$b = $a > 15 ? 20 : 5;
print ("Value of b is " . $b);
?>

Output:
Value of b is 5
Example2:
<?php
$age = 20;
print ($age >= 18) ? "Adult" : "Not Adult";
?>

Output:
Adult

Looping Statements:
Loops are used to decide how many times to execute a block of code.

Loop statements are specifically designed to enable you to perform repetitive


tasks because they continue to operate until a specified condition is achieved or
until you explicitly choose to exit the loop.

while Statement
A while statement executes a block of statements as long as the expression
evaluates to true.
while (expression) {
// do something
}

Each execution of a code block within a loop is called an iteration. While


comprises a initial value, a condition and the increment.

testwhile.php
<?php
$n=1;
while($n<=10){
echo "$n<br/>";
$n++;
}
?>

Output:
1
2
3
4
5
6
7
8
9
10
testwhile1.php - A while Statement
1: <?php
2: $counter = 1;
3: while ($counter <= 12) {
4: echo $counter.” times 2 is “.($counter * 2).”<br />”;
5: $counter++;
6: }
7: ?>

Output:
1 times 2 is 2
2 times 2 is 4
3 times 2 is 6
4 times 2 is 8
5 times 2 is 10
6 times 2 is 12
7 times 2 is 14
8 times 2 is 16
9 times 2 is 18
10 times 2 is 20
11 times 2 is 22
12 times 2 is 24

do...while Statement
A do...while statement looks like a while statement. The difference between the
two is that the code block in the do…while is executed before the truth test:
do {
// code to be executed
} while (expression);

This type of statement is useful when you want the code block to be executed at
least once, even if the while expression evaluates to false.

testdowhile.php

<?php
$n=1;
do{
echo "$n<br/>";
$n++;
}while($n<=10);
?>

Output:
1
2
3
4
5
6
7
8
9
10
testdowhile1.php - The do...while Statement
1: <?php
2: $num = 1;
3: do {
4: echo “The number is: “.$num.”<br />”;
5: $num++;
6: } while (($num > 200) && ($num < 400));
7: ?>

Output:
The number is: 1

The do...while statement tests whether the variable $num contains a value that is
greater than 200 and less than 400. Line 2 initializes $num to 1, so this
expression returns false. Nonetheless, the code block is executed at least one
time before the expression is evaluated, so the statement prints a single line to
the browser.

for Statement
In While, a variable was initialized outside the while statement and then tested
within its expression and incremented within the code block.
With a for statement, you can write initialization, test expression and increment
in a single line of code.
for (initialization expression; test expression; modification expression) {
// code to be executed
}

The expressions within the parentheses of the for statement are separated by
semicolons.
Usually, the first expression initializes a counter variable, the second expression
is the test condition for the loop, and the third expression increments the
counter.

testfor.php

<?php
for($n=1;$n<=10;$n++){
echo "$n<br/>";
}
?>

Output:
1
2
3
4
5
6
7
8
9
10

testfor1.php - Using the for Statement


1: <?php
2: for ($counter=1; $counter<=12; $counter++) {
3: echo $counter.” times 2 is “.($counter * 2).”<br />”;
4: }
5: ?>

Output:
1 times 2 is 2
2 times 2 is 4
3 times 2 is 6
4 times 2 is 8
5 times 2 is 10
6 times 2 is 12
7 times 2 is 14
8 times 2 is 16
9 times 2 is 18
10 times 2 is 20
11 times 2 is 22
12 times 2 is 24

Introduction to Arrays:

PHP array is an ordered map (contains value on the basis of key). It is used to
hold multiple values of similar type in a single variable.

Advantages

Less Code: We don't need to define multiple variables.

Easy to traverse: By the help of single loop, we can traverse all the elements of
an array.

Sorting: We can sort the elements of array.


What is array?An array is a special variable that we use to store or hold more
than one value in a single variable without having to create more variables to
store those values.

Arrays are indexed, which means that each entry is made up of a key and a
value. The key is the index position, beginning with 0 and increasing
incrementally by 1 with each new element in the array.

Creating Arrays
We can create an array using the following two ways:
1. array() function or
2. array operator [ ].

The array() function is used to create a new array and populate it with more
than one element.

Ex:-
$rainbow = array(“red”, “orange”, “yellow”, “green”, “blue”, “indigo”,
“violet”);

The array operator “[ ]” is used to create a new array with just one element, or
when you want to add to an existing array element.

Ex:-
$rainbow[ ] = “red”;
$rainbow[ ] = “orange”;
$rainbow[ ] = “yellow”;
$rainbow[ ] = “green”;
$rainbow[ ] = “blue”;
$rainbow[ ] = “indigo”;
$rainbow[ ] = “violet”;

PHP handles the numbering for the array when positions are not specified.
Values starting at index position 0 (zero).
Or
You also can specify index number as below
$rainbow[0] = “red”;
$rainbow[1] = “orange”;
$rainbow[2] = “yellow”;
$rainbow[3] = “green”;
$rainbow[4] = “blue”;
$rainbow[5] = “indigo”;
$rainbow[6] = “violet”;

In the following example, in the first line, six elements are added to the array
using array(), and one more element is added to the end of the array in the
second line using array operator:

$rainbow = array(“red”, “orange”, “yellow”, “green”, “blue”, “indigo”);


$rainbow[ ] = “violet”;

Ex:
<?php
$rainbow = array("red", "orange", "yellow", "green", "blue", "indigo");
$rainbow[] = "violet";

echo $rainbow[1];
?>
Output:
orange
Ex:
<?php
$rainbow = array("red", "orange", "yellow", "green", "blue", "indigo");
$rainbow[] = "violet";
$arrSize = count($rainbow);
echo "Array Size=$arrSize <br/>";
for ($i = 0; $i < $arrSize; $i++) {
echo $rainbow[$i] . "<br/>";
}
?>

Output:
Array Size=7
red
orange
yellow
green
blue
indigo
violet
Accessing array elements:
To access elements of array in PHP, you can use array variables followed by
index which is enclosed in square brackets.

The syntax to access element at a specific index in a given array is


$element = $array[$index]
The index starts from 0 and increments by 1 from left to right of the array. So,
the index of first element is 0, the index of second element is 1, the index of
third element is 2, and so on.
In this example, we will take an array of strings, and access second and fourth
elements using indexes 1 and 3 respectively.
EX:
<?php
$array = ["apple", "banana", "orange", "mango", "guava"];
$second_element = $array[1];
$fourth_element = $array[3];
echo $second_element;
echo "<br>";
echo $fourth_element;
?>
Output:
banana
mango

Types of arrays:
There are 3 types of array in PHP.
Indexed Array
Associative Array
Multidimensional Array

Indexed Array
PHP index is represented by number which starts from 0. We can store number,
string and object in the PHP array. All PHP array elements are assigned to an
index number by default.
There are two ways to define indexed array:
1st way:
$season=array("summer","winter","spring","autumn");
2nd way:
$season[0]="summer";
$season[1]="winter";
$season[2]="spring";
$season[3]="autumn";

Example
<?php
$season=array("summer","winter","spring","autumn");
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
?>

Output:
Season are: summer, winter, spring and autumn

PHP Associative Array


We can associate name with each array elements in PHP using => symbol.
There are two ways to define associative array:
1st way:
$salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
2nd way:
$salary["Sonoo"]="350000";
$salary["John"]="450000";
$salary["Kartik"]="200000";
Example
<?php
$salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
echo "John salary: ".$salary["John"]."<br/>";
echo "Kartik salary: ".$salary["Kartik"]."<br/>";
?>

Output:
Sonoo salary: 350000
John salary: 450000
Kartik salary: 200000

Difference between Indexed array and associative array:


Indexed Array
 The keys of an indexed array are integers which start at 0.
 They are like single-column tables.
 They are not maps.
Associative Array
 Keys may be strings in the case of an associative array.
 They are like two-column tables.
 They are known as maps.

Multidimensional Arrays
The multidimensional array is an array in which each element can also be an
array.
If each set of key/value pairs constitutes a dimension, a multidimensional array
holds more than one series of these key/value pairs.

Ex:-
<?php
// Define a multidimensional array
$values = array(
array(
"i1" => "10",
"i2" => "20",
),
array(
"i3" => "30",
"i4" => "40",
)
);
// Access nested value
echo "i1= " . $values[0]["i1"]."<br/>";
echo "i4= " . $values[1]["i4"];
?>

Output:
i1= 10
i4= 40

Manipulating arrays:
Besides the built-in array functions, PHP offers several techniques to
manipulate arrays efficiently. Here are a few notable techniques:
 Looping: We can iterate over an array using foreach loop to perform
specific operations on each element.
 Slicing: We can extract a portion of an array using
the array_slice() function.
 Flattening: We can convert a multidimensional array into a single-
dimensional array using the array_merge() function.
 Searching: We can search for a particular value or key in an array using
functions like in_array(), array_search(), or array_key_exists().

These techniques provide a powerful way to manipulate and transform arrays


according to our needs.

Displaying array elements:


To print an array in PHP, you can use the built-in print_r() function, which
prints or displays information about a variable, including its type and value.

PHP print_r() Syntax

print_r(variable, return)

Where:

 variable: specifies the array about which we want to get information


 return (Optional): when set to "True", this function will return
information, but not print it. The default value is "False".

Examaple:

<?php $colors = array("black", "white", "grey");

print_r($colors);
?>

#output: Array #( # [0] => black # [1] => white # [2] => grey #)

To display information about an array in PHP, you can use the var_dump()
function, which dumps structured information such as the type and value of a
given variable. Arrays and objects are explored recursively with indented values
to show structure.

PHP var_dump() Syntax

var_dump(variable1, variable2, ...);

Where:

 variable: defines an array to display information

<?php $colors = array("black", "white", "grey");

echo var_dump($colors);

?>

#output: array(3) { # [0]=> # string(5) "black" # [1]=> # string(5) "white" #


[2]=> # string(4) "grey" #}

Printing the elements of an array using a foreach loop


In some cases, you may want to display additional (for example, dynamically
calculated) information about the elements of an array in PHP. In such a case,
you can use a foreach loop, which provides a simple iteration of the elements of
an array.

<?php $colors = array("black", "white", "grey");


foreach ($colors as $value)

echo "$value ";

?>

#output: black white grey.

Using Array functions:

Some of the more common and useful functions of arrays are :

count() and sizeof()—Each of these functions counts the number of elements in


an array; they are aliases of each other. Given the following array

$colors = array(“blue”, “black”, “red”, “green”);

both count($colors); and sizeof($colors); return a value of 4.

each() and list()—These functions (well, list() is a language construct that


looks like a function) usually appear together, in the context of stepping through
an array and returning its keys and values. You saw an example of this
previously, where we stepped through the $c array and printed its contents.

foreach()—This control structure (that looks like a function) is used to step


through an array, assigning the value of an element to a given variable, as you
saw in the previous section.
reset()—This function rewinds the pointer to the beginning of an array, as in
this example:

reset($character);

This function proves useful when you are performing multiple manipulations on
an array, such as sorting, extracting values, and so forth.

array_push()—This function adds one or more elements to the end of an


existing array, as in this example:

array_push($existingArray, “element 1”, “element 2”, “element 3”);

array_pop()—This function removes (and returns) the last element of an


existing array, as in this example:

$last_element = array_pop($existingArray);

array_unshift()—This function adds one or more elements to the beginning of


an existing array, as in this example:

array_unshift($existingArray, “element 1”, “element 2”, “element 3”);

array_shift()—This function removes (and returns) the first element of an


existing array, as in this example, where the value of the element in the first
position of $existingArray is assigned to the variable $first_element:

$first_element = array_shift($existingArray);
array_merge()—This function combines two or more existing arrays, as in this
example:

$newArray = array_merge($array1, $array2);

array_keys()—This function returns an array containing all the key names


within a given array, as in this example:

$keysArray = array_keys($existingArray);

array_values()—This function returns an array containing all the values within


a given array, as in this example:

$valuesArray = array_values($existingArray);

shuffle()—This function randomizes the elements of a given array. The syntax


of this function is simply as follows:

shuffle($existingArray);

Ex:
<?php
$rainbow = array("red", "orange", "yellow", "green", "blue", "indigo");
$rainbow[] = "violet";
array_push($rainbow, "element 1", "element 2", "element 3");
$arrSize = count($rainbow);
echo "Array Size=$arrSize <br/>";
for ($i = 0; $i < $arrSize; $i++) {
echo $rainbow[$i] . "<br/>";
}

$last_element = array_pop($rainbow);
$arrSize = count($rainbow);
echo "Array Size=$arrSize <br/>";
for ($i = 0; $i < $arrSize; $i++) {
echo $rainbow[$i] . "<br/>";
}
?>

Output:
Array Size=10
red
orange
yellow
green
blue
indigo
violet
element 1
element 2
element 3

Array Size=9
red
orange
yellow
green
blue
indigo
violet
element 1
element 2

Include and requiring files:

Include Statement

The „include‟ or „require‟ statement can be used to insert the content of one
PHP file into another PHP file (before the server executes it). Except in the case
of failure, the „include‟ and „require statements‟ are identical:
Include in PHP will only generate an alert (E_WARNING), and the script will
proceed.
Require will produce a fatal error (E_COMPILE_ERROR) and interrupt the
script.
If the include statement appears, execution should continue and show users the
output even if the include file is missing. Otherwise, always use the required
declaration to include the main file in the flow of execution while coding
Framework, CMS, or a complex PHP program. This will help prevent the
application's protection and reputation from being jeopardized if one key file is
corrupted.

The include() function copies all of the text from a given file into the file that
uses the include function. It produces an alert if there is a problem loading a
file; however, the script will still run.

Advantages of Include() in PHP


Code Reusability: We may reuse HTML code or PHP scripts in several PHP
scripts with the aid of the „include‟ and „require‟ build.

Easy to Edit: If you want to alter anything on a website, you can modify the
source file used with all of the web pages rather than editing each file
individually.

include is a keyword to include one PHP file into another PHP file. While
including the content of the included file will be displayed in the main file. The
below example code will demonstrate the concept of PHP include.

Syntax:
include 'file_name';
Or
require 'file_name';
Code:Page1.php
<?php
echo "<p>welcome to my webpage</p>";
?>
Main.php
<html>
<body>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>
<p>Some more text.</p>
<?php include 'Page1.php';?>
</body>
</html>
Explanation:In the above code, there are two files, that is, Page1.php and
Main.php. In the Main.php file, the Page1.php has been included with the help
of line <?php include „Page1.php‟;?>

Output:

PHP_Include_1

PHP Require

The PHP require function is similar to the include function, which is used to
include files. The only difference is that if the file is not found, it prevents the
script from running, while include does not.

The require() function copies all of the text from a given file into the file that
uses the include function. The require() function produces a fatal error and stops
the script's execution if there is a problem loading a file. So, apart from how
they treat error conditions, require() and include() are identical. Since scripts do
not execute if files are missing or misnamed, the require() function is
recommended over include().

Syntax:
require 'file_name';
Or
require ('file_name');
Code:
Menu1.html:
<html>
<body>
<ahref="http://www.google.com">Google</a> |
<ahref="http://www.yahoo.com">Yahoo</a> |
<ahref="http://www.maps.com">Maps</a> |
<ahref="http://www.tutorial.com">Tutorial</a>
</body>
</html>
Main.html:
<html>
<body>
<h1>welcome</h1>
<?php require("menu1.html"); ?>
</body>
</html>
Output:PHP_Include_2

Implicit and explicit type casting:

PHP type casting refers to change the variable from one data type to
another data type.

This is the process of changing a variable's data type to another data


type automatically or manually. This process is known as typecasting
and it can be done in two ways.

1. Implicit Casting (Automatic)

2. Explicit Casting (Manual)

Implicit Casting
Implicit data typecasting can be done by PHP automatically. Let us
understand it with the help of an example. Let us perform the divide
operation by two integer numbers then in this case result might be
either an integer or float number.

Ex:
<?php
$x = 8;
$y = 4;
var_dump($x / $y); // 8/4 = 2 (int)
var_dump($y / $x); // 4/8 = 0.5 (float)
?>
Explicit Casting
Explicit casting can be customized by the user. Users can change
variable types from one data type to another data type with the help of
PHP methods.
Let us see different casting methods.
Cast Description
(int) or (integer) : Cast to an integer.
(float) or (double) or (real) :Cast to a float.
(bool) or (boolean) : Cast to a boolean.
(string) :Cast to a string.
(array) :Cast to an array.
(object) :Cast to an object.

You might also like