0% found this document useful (0 votes)
9 views61 pages

PHP JT 2nd Unit

The document provides an overview of programming with PHP, focusing on conditional statements, loops, and arrays. It details various conditional statements like if, if...else, and switch, as well as loop types such as while, do...while, and for. Additionally, it explains how to create and manipulate indexed, associative, and multidimensional arrays in PHP.

Uploaded by

dhanrajbhandge00
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)
9 views61 pages

PHP JT 2nd Unit

The document provides an overview of programming with PHP, focusing on conditional statements, loops, and arrays. It details various conditional statements like if, if...else, and switch, as well as loop types such as while, do...while, and for. Additionally, it explains how to create and manipulate indexed, associative, and multidimensional arrays in PHP.

Uploaded by

dhanrajbhandge00
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
You are on page 1/ 61

Unit-2 Programming with PHP

PHP Conditional Statements


● Very often when you write code, you want to perform different actions for
different conditions.
● You can use conditional statements in your code to do this.

In PHP we have the following conditional statements:

1. if statement - executes some code if one condition is true


2. if...else statement - executes some code if a condition is true and another
code if that condition is false
3. if...elseif...else statement - executes different codes for more than two
conditions
4. switch statement - selects one of many blocks of code to be executed

PHP - The if Statement


● The if statement executes some code if one condition is true.

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

Example:
PHP - The if...else Statement
● The if...else statement executes some code if a condition is true and another
code if that condition is false.

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

Example
PHP - The if...elseif...else Statement
● The if...elseif...else statement executes different codes for more than two
conditions.

Syntax
if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
// code to be executed if first condition is false and this condition is true;
} else {
// code to be executed if all conditions are false;
}

Example
Nested If
● You can have if statements inside if statements, this is called nested if
statements.

Example:
● An if inside an if:
The PHP switch Statement
● Use the switch statement to select one of many blocks of code to be
executed.

Syntax
switch (expression)
{
case label1:
//code block
break;
case label2:
//code block;
break;
case label3:
//code block
break;
default:
//code block
}

This is how it works:


● The expression is evaluated once
● The value of the expression is compared with the values of each case
● If there is a match, the associated block of code is executed
● The break keyword breaks out of the switch block
● The default code block is executed if there is no match

Example
The break Keyword
● When PHP reaches a break keyword, it breaks out of the switch block.
● This will stop the execution of more code, and no more cases are tested.
● The last block does not need a break, the block breaks (ends) there anyway.

The default Keyword


The default keyword specifies the code to run if there is no case match:

Example
If no cases get a match, the default block is executed:
The ? Operator:(Ternary Operator)
● The ternary operator in php is a concise way to write conditional
statements that improve code readability and effectiveness.
● It is an alternative to the “if-else” conditional statement of php.
● The ternary operator is a shortcut operator used for shortening the
conditional statements.
● It decreases
● the length of the code performing conditional operations.
● Syntax:
Condition ? statement1 statement2;
● Example:
<?php
$age=17;
$type=$age>=16? "Adult" : "child";
echo $type;
?>

PHP Loops
● Often when you write code, you want the same block of code to run over
and over again a certain number of times.
● So, instead of adding several almost equal code-lines in a script, we can use
loops.
● Loops are used to execute the same block of code again and again, as long
as a certain condition is true.

In PHP, we have the following loop types:

while - loops through a block of code as long as the specified condition is true
do...while - loops through a block of code once, and then repeats the loop as
long as the specified condition is true
for - loops through a block of code a specified number of times

The PHP while Loop


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

Example:

Print $i as long as $i is less than 6:


Note: remember to increment $i, or else the loop will continue forever.

● The while loop does not run a specific number of times, but checks after
each iteration if the condition is still true.
● The condition does not have to be a counter, it could be the status of an
operation or any condition that evaluates to either true or false.

The break Statement


● With the break statement we can stop the loop even if the condition is still
true:

Example
Stop the loop when $i is 3:
The continue Statement
● With the continue statement we can stop the current iteration, and continue
with the next:

Example
Stop, and jump to the next iteration if $i is 3:
The PHP do...while Loop
● The do...while loop will always execute the block of code at least once, it
will then check the condition, and repeat the loop while the specified
condition is true.

Example
● Print $i as long as $i is less than 6:
The break Statement
● With the break statement we can stop the loop even if the condition is still
true:

Example
● Stop the loop when $i is 3:
The continue Statement
● With the continue statement we can stop the current iteration, and continue
with the next:

Example
● Stop, and jump to the next iteration if $i is 3:
The PHP for Loop
● The for loop is used when you know how many times the script should run.

Syntax
for (expression1, expression2, expression3) {
// code block
}

This is how it works:

● expression1 is evaluated once


● expression2 is evaluated before each iteration
● expression3 is evaluated after each iteration

Example

Print the numbers from 0 to 10:


Example Explained
● The first expression, $x = 0;, is evaluated once and sets a counter to 0.
● The second expression, $x <= 10;, is evaluated before each iteration, and
the code block is only executed if this expression evaluates to true.
● In this example the expression is true as long as $x is less than, or equal to,
10.
● The third expression, $x++;, is evaluated after each iteration, and in this
example, the expression increases the value of $x by one at each iteration.

The break Statement:


● With the break statement we can stop the loop even if the condition is still
true:

Example

Stop the loop when $i is 3:


The continue Statement
● With the continue statement we can stop the current iteration, and continue
with the next:
Example
● Stop, and jump to the next iteration if $i is 3:
What is an Array?
● Array is a collection of homogeneous data elements.
● An array is a special variable that can hold many values under a single
name, and you can access the values by referring to an index number or
name.
● Example:
<?php
$students=array(
array("name"=>"john","age"=>30),
array("name"=>"alice","age"=>20),
array("name"=>"eve","age"=>50)
);
print_r($students);
?>

Creating Arrays in PHP:


1. Using the array() function:
● You can create the array() function to create an array.
● You can initialize it with values or leave if empty and then add
elements later.
● Syntax:
$Variable_name=array( Array Elements );

● Example:
Indexed array:

<?php
$student=array(20,30,40);
print_r($student);
?>
Associative array:

<?php
$f1=array("name"=>"abc","age"=>80);
print_r($f1);
?>

2. Using Short Array Syntax:


● You can use the short array syntax[] to create an array.
● Here we are directly assigning the values to the variable in the square
brackets[].
● Syntax:
$Variable_name=[ Array Elements ];
● Example:

Indexed array:

<?php
$a1=[10,30,20,40];
print_r($a1);
?>

Associative array:

<?php
$f1=["name"=>"abc","age"=>80];
print_r($f1);
?>

3. Using the range() function:


● The range() function creates an array containing a range of elements.
● Syntax:
$var_name=range(attay_elements);
● Example:
<?php
$f1=range(1,5);
print_r($f1);
?>

4. Using the array_fill() function:


● The array_fill function creates an array with a specified number of
elements, all initialized with the same value.
● Syntax:
array_fill(index, number, value);
● Example:

<?php
$value=array_fill(0,3,"Default");
print_r($value);
?>

Accessing array elements in php:


● To access an array item, you can refer to the index number for indexed
arrays, and the key name for associative arrays.
● Example:
Indexed array:

Associative array:

Execute a Function Item:


● Array items can be of any data type, including function.
● Indexed array: To execute such a function, use the index number
followed by parentheses ():
● Example:

● Associative array: Use the key name when the function is an item in an
associative array.
● Execute function by referring to the key name:
Loop Through an Associative Array:
● Associative array: To loop through and print all the values of an
associative array, you can use a foreach loop, like this:

Loop Through an Indexed Array:


● Indexed array:To loop through and print all the values of an
indexed array, you can use a foreach loop, like this:
PHP Array Types
In PHP, there are three types of arrays:

Indexed arrays - Arrays with a numeric index


Associative arrays - Arrays with named keys
Multidimensional arrays - Arrays containing one or more arrays

PHP Indexed Arrays


● In indexed arrays each item has an index number.
● By default, the first item has index 0, the second item has item 1, etc.
Access Indexed Arrays
● To access an array item you can refer to the index number.

Change Value
● To change the value of an array item, use the index number:
Loop Through an Indexed Array
● To loop through and print all the values of an indexed array, you
could use a foreach loop, like this:

PHP Associative Arrays


● Associative arrays are arrays that use named keys that you assign to
them.

Access Associative Arrays


● To access an array item you can refer to the key name.

Change Value
● To change the value of an array item, use the key name:
Loop Through an Associative Array
● To loop through and print all the values of an associative array, you
could use a foreach loop, like this:

PHP - Multidimensional Arrays


● A multidimensional array is an array containing one or more arrays.
● PHP supports multidimensional arrays that are two, three, four, five,
or more levels deep.
● However, arrays more than three levels deep are hard to manage for
most people.
Creating and Accessing Multidimensional array elements:

● Creating Multidimensional array Using Nested array function.


● We can access the array elements using index value row and column.like
echo $matrix[0][1];
● Example:

<?php
$matrix=array(array(1,2,3),
array(4,5,6),
array(7,8,9));
echo $matrix[0][1];
echo "<br>";
echo $matrix[0][0];
echo "<br>";
?>

● We can access the array elements by using print_r() function.


● Example:
<?php
$matrix=array(array(1,2,3),
array(4,5,6),
array(7,8,9));
print_r($matrix);
echo "<br>";
?>

● We can access the array elements by using nested for loop to print row and
column like matrix format.
● Example: Indexed Array:
<?php
$matrix=array(array(1,2,3),
array(4,5,6),
array(7,8,9));
for($i=0;$i<3;$i++)
{
for($j=0;$j<3;$j++)
{
echo $matrix[$i][$j]." ";
}
echo "<br>";
}
?>
Associative array:
<?php
$students=array(
array("name"=>"john","age"=>30),
array("name"=>"alice","age"=>20),
array("name"=>"eve","age"=>50)
);
print_r($students);
echo "<br>";
foreach($students as $row)
{
foreach($row as $key=>$value){
echo " $key:$value ";
}
echo "<br>";
}
?>
Updating the array elements:
● We can update the array elements by using the array index value.
● Example:
<?php
$cars = array (
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
echo "before update the array elements<br>";
for($row=0;$row<3;$row++)
{
for($col=0;$col<3;$col++)
{
echo $cars[$row][$col]." ";
}
echo "<br>";
}
echo "after update the array elements<br>";
$cars[0][1]=20;
for($row=0;$row<3;$row++)
{
for($col=0;$col<3;$col++)
{
echo $cars[$row][$col]." ";
}
echo "<br>";
}
?>

Array functions:

1. array()
● The array() function is used to create an array.
● In PHP, there are three types of arrays:
● Indexed arrays - Arrays with numeric index
● Associative arrays - Arrays with named keys
● Multidimensional arrays - Arrays containing one or more arrays
● Syntax: Syntax for indexed arrays:
array(value1, value2, value3, etc.)
-
● Syntax for associative arrays:
array(key=>value,key=>value,key=>value,etc.)
2. array_fill() function:
● The array_fill() function fills an array with values.
● Syntax
array_fill(index, number, value)

3. array_push ()
● The array_push() function inserts one or more elements to the end
of an array.
● Tip: You can add one value, or as many as you like.
● Note: Even if your array has string keys, your added elements will
always have numeric keys (See example below).
4. array_pop()
● The array_pop() function deletes the last element of an array.
● Syntax:
array_pop(array)
● Example:
5. array_revers():
● The array_reverse() function returns an array in the reverse order.
● Syntax
array_reverse(array_var);
Associative array:

Indexed array:

<?php
$a=array(1,2,3,4,5,6);
print_r($a);
echo "<br>";
print_r(array_reverse($a));
?>

Output:

6. array_search() Function
● The array_search() function searches an array for a value and
returns the key.
● Example for associative array:

● The array_search() function searches an array for a value and


returns the index.
● Example for Indexed array.
<?php
$a=array(1,2,3,4,5,6);
print_r($a);
print_r(array_search(6,$a));
?>
Output:

7. array_slice() Function
● The array_slice() function returns selected parts of an array.
● Example:
Start the slice from the third array element, and return the rest of the
elements in the array:
Start the slice from from the second array element, and return only
two elements:

Using a negative start parameter:

With both string and integer keys:


<!DOCTYPE html>
<html>
<body>
<?php
$a=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow","e"=>"brown
");
print_r(array_slice($a,1,2));

$a=array("0"=>"red","1"=>"green","2"=>"blue","3"=>"yellow","4"=>"brown
");
print_r(array_slice($a,1,2));
?>
</body>
</html>

8. array_fill_keys() Function:
● The array_fill_keys() function fills an array with values,
specifying keys.
● Syntax
array_fill_keys(keys, value)
● Example:
Fill an array with values, specifying keys:
Example 2:
<?php
$keys=array("a",1,"2");
print_r(array_fill_keys($keys,"php"))
?>

Example 2:
<?php
$keys=array("a",1,"2");
$val=array("abc","xyz","jkl");
print_r(array_fill_keys($keys,$val))
?>

9. array_intersect() Function
● The array_intersect() function compares the values of two (or
more) arrays, and returns the matches.
● This function compares the values of two or more arrays, and
return an array that contains the entries from array1 that are
present in array2, array3, etc.
Compare the values of two arrays, and return the matches:
Compare the values of three arrays, and return the matches:

10. array_keys() Function:


● The array_keys() function returns an array containing the keys.
● Syntax
array_keys(array, value)
● Example:
Return an array containing the keys:

Using the value parameter:


11. array_shift() Function
● The array_shift() function removes the first element from an array,
and returns the value of the removed element.
● Syntax
array_shift(array)

Note: If the keys are numeric, all elements will get new keys, starting
from 0 and increases by 1 (See example below).
Using numeric keys:

12. array_unshift() Function


● The array_unshift() function inserts new elements to an array.
● The new array values will be inserted in the beginning of the array.
● Tip: You can add one value, or as many as you like.
● Syntax
array_unshift(array, value1, value2, value3, ...)

Using numeric keys:


13. array_unique() Function
● The array_unique() function removes duplicate values from an array.
● If two or more array values are the same, the first appearance will be
kept and the other will be removed.

PHP Include() Function:


● The include statement takes all the text/code that exists in the
specified file and copies it into the file that uses the include
statement.
● Including files saves a lot of work.
● This means that you can create a standard header, footer, or menu
file for all your web pages. Then, when the header needs to be
updated, you can only update the header include file.
Syntax
include 'filename';
Example 1: header.php
<header>
<h1>
Welcome to Php header file
</h1>
</header>

Footer.php

<footer>
<p>This is footer file</p>
</footer>
include.php

<?php
include('header.php');
echo "this is main content";
include('footer.php');
?>

If the included file is not exits :


header.php
<header>
<h1>
Welcome to Php header file
</h1>
</header>

Footer.php

<footer>
<p>This is footer file</p>
</footer>

include.php
<?php
include('header.php');
echo "this is main content";
include('nofile.php');
include('footer.php');
?>
require();
● The require statement is also used to include a file into the PHP
code.
● However, there is one big difference between include and require;
when a file is included with the include statement and PHP cannot
find it, the script will continue to execute:
● If we do the same example using the require statement, the echo
statement will not be executed because the script execution dies after
the require statement returned a fatal error:
header.php
<header>
<h1>
Welcome to Php header file
</h1>
</header>

footer.php

<footer>
<p>This is footer file</p>
</footer>

require.php

<?php
require('header.php');
echo "this is main content";
require('footer.php');
?>
If the required file is not exits:
header.php
<header>
<h1>
Welcome to Php header file
</h1>
</header>

footer.php
<footer>
<p>This is footer file</p>
</footer>

require.php

<?php
require('header.php');
echo "this is main content";
require('nofile.php');
require('footer.php');
?>
Fatal error:
● A fatal error is another type of error, which occurs due to the use
of undefined functions or files.
● The PHP compiler understands the PHP code but also
recognizes the undefined function.
● This means that when a function is called without providing its
definition, the PHP compiler generates a fatal error.

What is Type Casting?


● Type casting is a concept in programming where you change the data
type of a variable from one type to another.
There are two types of type casting: implicit and explicit.
1. Implicit Type Casting:
2. Explicit Type Casting:
Implicit Type Casting:
● In implicit type casting, the programming language automatically
converts data from one type to another if needed.
● For example, if you have an integer variable and you try to assign it
to a float variable, the programming language will automatically
convert the integer to a float without you having to do anything.
● Example:
<?php
function palindrome($n)
{
$number = $n;
$sum = 0;
while (floor($number)) {
$rem = $number % 10;
$sum = $sum * 10 + $rem;
$number = $number / 10;
}
return $sum;
}
$n=readline('Enter a num1:');
$num = palindrome($n);
if ($n == $num) {
echo "$n is a Palindrome number";
} else {
echo "$n is not a Palindrome";
}
?>
Explicit Type Casting:
● Explicit type casting, also known as type conversion, occurs when
the programmer explicitly converts a value from one data type to
another.
● Unlike implicit type casting, explicit type casting requires the
programmer to specify the desired data type conversion.
Change Data Type
Casting in PHP is done with these statements:
● (string) - Converts to data type String
● (int) - Converts to data type Integer
● (float) - Converts to data type Float
● (bool) - Converts to data type Boolean
● (array) - Converts to data type Array
● (object) - Converts to data type Object
● (unset) - Converts to data type NULL
To cast to string, use the (string) statement:

To cast to integer, use the (int) statement:


Converting Objects into Arrays:

You might also like