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

Week 03 Lec 01 Arrays

week 03 lec 01 Arrays

Uploaded by

Aftab Jamali
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Week 03 Lec 01 Arrays

week 03 lec 01 Arrays

Uploaded by

Aftab Jamali
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 68

Web Development week

02
SADAM HUSSAIN
Exercise

A program to check 1233456 is odd or even is shown ?


Exercise
A program to check 1233456 is odd or even is shown ?
Answer:
$number=1233456;
if($number%2==0)
{
echo "$number is Even Number";
}
else
{
echo "$number is Odd Number";
}
While Loop statement
Example practice:

1 write program yo output following


While Loop statement
Example practice:

1. Answer

for($x=1;$x<=5;$x++)

for ($y=1;$y<=$x;$y++)

echo "*";

if($y< $x)

{ echo " ";

echo "\n";

}
While Loop statement
Example practice:

2 : Write a factorial program using for loop in php ….. ??

Fac of 3: 3*2*1

Fac of 5: 5*4*3*2*1

Fac of 6: 6*5*4*3*2*1
While Loop statement
Example practice:

2 : Write a factorial program using for loop in php …. Answer

$num = 3;

$factorial = 1;

for ($x=$num; $x>=1; $x--)

$factorial = $factorial * $x;

echo "The factorial of $num is $factorial";


While Loop statement

The while statement will execute a block of code if and as long as a test
expression is true.

If the test expression is true, then the code block will be executed. After the
code has executed the test expression will again be evaluated and the loop
will continue until the test expression is found to be false
While Loop statement
Syntax
while (condition is true) {
code to be executed;
}

Example:

<?php
$x = 1;

while($x <= 15) {


echo "The number is: $x <br>";
$x++;
}
?>
While Loop statement
Do…While Loop statement
The do...while loop will always execute the block of code once, it will then check the condition, and
repeat the loop while the specified condition is true.

Syntax
do {
code to be executed;
} while (condition is true);
Example
<?php
$x = 1;

do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 20);
?>
Do…While Loop statement

What will be the output of the following PHP code?

<?php
$i = 0
do
{
print "hi";
$i++;
}
while ($i != 3);
?>
Do…While Loop statement

What will be the output of the following PHP code?

<?php
$i = 0
while ($i < 3)
{
print "hi";
$i--;
}
print "hello"
?>
Do…While Loop statement

What will be the output of the following PHP code?

<?php
$i = "";
while($i)
{
print "hi";
}
print "hello";
?>
PHP Functions

•A function is a block of statements that can be used


repeatedly in a program.
•A function will not execute automatically when a page loads.
•A function will be executed by a call to the function.

Syntax
function functionName() {
code to be executed;
}
PHP Functions

<?php
function abc() {
echo "Hello world!";
}

abc(); // call the function


?>
PHP Function Arguments
Arguments are specified after the function name, inside the parentheses. You can add as many arguments as
you want, just separate them with a comma.

Ex1:
function abc($fname) {
echo "$fname.<br>";
}

abc(“ali");
abc(“hamza");

Ex2:

function abcd($fname, $year) {


echo "$fname. Born in $year <br>";
}

abcd(“ali", “2001");
abcd(“hamza", “2002");
PHP Function
PHP is a Loosely Typed Language. PHP automatically associates a data type to the variable, depending on its value

Ex1:
function numbersAdd($a,$b) {
return $a + $b;
}
echo numbersAdd(5, "5 days");

// strict is NOT enabled "5 days" is changed to int(5), and it will


return 10
PHP Function
To specify strict we need to set declare(strict_types=1);. This must be on the very first line of the PHP file.

Ex1:
declare(strict_types=1); // strict requirement

function numbersAdd(int $a, int $b) {


return $a + $b;
}
echo numbersAdd(5, "5 days");

// since strict is enabled and "5 days" is not an integer, an error will
be thrown
PHP Function Arguments
Default Argument Value

Ex1:
declare(strict_types=1); // strict requirement

function setHeight(int $minheight = 60) {


echo "The height is : $minheight <br>";
}

setHeight(50);
setHeight(100);
setHeight(30);
setHeight(); // will use the default value of 60
PHP FUNCTION Returning values
Returning values

Ex1:
declare(strict_types=1); // strict requirement
function add(int $x, int $y) {
$z = $x + $y;
return $z;
}

echo “15 + 8 = " . add(15, 8) . "<br>";


echo “5 + 3 = " . add(5, 3) . "<br>";
echo "20 + 14 = " . add(20, 14);
PHP example

Ex1:
Write a PHP script to print all even numbers between 1 to 20

Output: 2 4 6 8 10 12 14 16 18 20
PHP FUNCTION Returning values
Ex1: Solution
<?php
$num=0;
while ($num < 20) {
$num = $num +2;
echo $num, "\n";
}
?>
PHP example

Ex2:
Write a PHP script to print all odd numbers between 1 to 20

Output: 1 3 5 7 9 11 13 15 17 19
PHP FUNCTION Returning values
Ex2: Solution
<?php
$num = 1;
while ( $num <= 20 ) {
print "$num";
$num += 2;
}
?>
PHP FUNCTION

Ex3:

Write a PHP program to check if a person is eligible to vote


How to do it.. ?

• Minimum age required for vote is 18.


• You can use PHP Functions.
• You can use Decision Making Statements
PHP FUNCTION Returning values
Ex3: Solution
function check_vote() //function has been declared {
$name = "Rakesh"; $age = 19;
if ($age >= 18) {
echo $name . ", you Are Eligible For Vote";
} else {
echo $name . ", you are not eligible for vote. ";
}
}

check_vote(); //function has been called


PHP ARRAYS
An array stores multiple values in one single variable: An array is a special variable, which
can hold more than one value at a time.
PHP ARRAYS
An array stores multiple values in one single variable: An array is a special variable, which can
hold more than one value at a time.

In PHP, the array() function is used to create an array: but we can directly
create array like below:
<?php
$var[0] = "a";
$var[1] = "y";
$var[2] = "h";
$var[3] = "e";
$var[4] = "u";

echo $var[2];
// outout h
?>
PHP ARRAYS
An array stores multiple values in one single variable: An array is a special variable, which
can hold more than one value at a time.

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
ARRAYS- PHP Indexed Arrays
The index can be assigned automatically (index always starts at 0), like this:

Ex1:
There are two ways to create indexed arrays:
$color = array(“red", “green", “blue");
$color[0] = “red";
$color[1] = "green";
$color[2] = "blue";

echo “value at index 0 and 1 " . $color[0] . ", " . $color[1] . " and at 2 " . $color[2] . ".";

The count() Function


The count() function is used to return the length (the number of elements) of an array:
$color = array("red", "green", "blue");
echo count($color);
ARRAYS- PHP Indexed Arrays
Loop Through an Indexed Array

$color = array(“red", “green", “blue");


$arrlength = count($color);

for($x = 0; $x < $arrlength; $x++) {


echo $color[$x];
echo "<br>";
}

foreach($color as $x => $x_value) {


echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
ARRAYS- PHP Associative Arrays
Associative arrays are arrays that use named keys that you assign to them

There are two ways to create an associative array:

$age = array(“ali"=>"35", "taha"=>"37", "hamza"=>"43");

or:
$age['ali'] = "35";
$age[‘taha'] = "37";
$age[‘hamza'] = "43";

$age = array(“ali"=>"35", “taha"=>"37", “hamza"=>"43");


echo “ali is " . $age[‘ali'] . " years old.";
ARRAYS- PHP Associative Arrays
Loop Through an Associative Array

$age = array(“ali"=>"35", “taha"=>"37", “hamza"=>"43");

foreach($age as $x => $x_value) {


echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
ARRAYS- PHP Multidimensional
It is the simplest form of a multidimensional array. It can be created using nested array. These type of arrays can be
Arrays
used to store any type of elements, but the index is always a number. By default, the index starts with zero
ARRAYS- PHP Multidimensional
A multidimensional array is an array containing one or more arrays.
Arrays

A two-dimensional array is an array of arrays (a three-dimensional array is an


array of arrays of arrays).

First, take a look at the following table:

Name math english


ali 75 90
Hamza 88 81
Taha 79 80
sana 83 77
ARRAYS- PHP Multidimensional
We can store the data from the table above in a two-dimensional array, like this:
Arrays

$marks = array (
array(“ali",75,90),
array(“hamza",88,81),
array(“taha",79,80),
array(“sana",83,77)
);
ow the two-dimensional $cars array contains four arrays, and it has two indices:
row and column.

To get access to the elements of the $cars array we must point to the two indices
(row and column):
ARRAYS- PHP Multidimensional
Arrays

echo $marks[0][0].": In stock: ".$marks[0][1].", sold: ".$marks[0][2].".<br>";

echo $marks[1][0].": In stock: ".$marks[1][1].", sold: ".$marks[1][2].".<br>";

echo $marks[2][0].": In stock: ".$marks[2][1].", sold: ".$marks[2][2].".<br>";

echo $marks[3][0].": In stock: ".$marks[3][1].", sold: ".$marks[3][2].".<br>";

How to print all values in loop ??


ARRAYS- PHP Multidimensional
Arrays

for ($row = 0; $row < 4; $row++) {


echo "<p><b>Row number $row</b></p>";
echo "<ul>";
for ($col = 0; $col < 3; $col++) {
echo "<li>".$cars[$row][$col]."</li>";
}
echo "</ul>";
}
ARRAYS- PHP Multidimensional
Arrays
$emp = array
(
array(1,"sonoo",400000),
array(2,"john",500000),
array(3,"rahul",300000)
);
for ($row = 0; $row < 3; $row++) {
for ($col = 0; $col < 3; $col++) {
echo $emp[$row][$col]." ";
}
echo "<br/>";
}
ARRAYS- Sort Functions For Arrays

sort() - sort arrays in ascending order

rsort() - sort arrays in descending order

asort() - sort associative arrays in ascending order, according to the value

ksort() - sort associative arrays in ascending order, according to the key

arsort() - sort associative arrays in descending order, according to the value

krsort()- sort associative arrays in descending order, according to

the key
ARRAYS- Sort Functions For Arrays

$numbers = array(4, 6, 2, 22, 11);


sort($numbers);

$cars = array("Volvo", "BMW", "Toyota");


rsort($cars);

$numbers = array(4, 6, 2, 22, 11);


rsort($numbers);

$age = array(“ali"=>"35", “babar"=>"37", “hamza"=>"43");


asort($age);

$age = array(“ali"=>"35", “babar"=>"37", “hamza"=>"43");


ksort($age);
ARRAYS- Sort Functions For Arrays

$age = array(“ali"=>"35", “babar"=>"37", “hamza"=>"43");


arsort($age);

$age = array(“ali"=>"35", “babar"=>"37", “hamza"=>"43");


krsort($age);

Count function : To count total values in a array

count($age);
ARRAYS- Functions For Arrays
Lets take array:

$age=array(“taha"=>"35",“hamza"=>"37",“ali"=>"43");

array_change_key_case() :

Changes all keys in an array to lowercase or uppercase

print_r(array_change_key_case($age,CASE_UPPER));
array_column() Function : Get column of last names from a recordset:
ARRAYS- Functions For Arrays
$a = array(
array(
'id' => 5698,
'first_name' => ’shahid',
'last_name' => ’ali',
),
array(
'id' => 4767,
'first_name' => ’Muhamamd',
'last_name' => ’taha',
),
array(
'id' => 3809,
'first_name' => ’Muhammad',
'last_name' => ’hamza',
)
);

$last_names = array_column($a, 'last_name');


print_r($last_names);

[0] => ali


[1] => taha
[2] => hamza
ARRAYS- Functions For Arrays
array_combine()

$fname=array(“ali",“taha",“hamza");
$age=array("35","37","43");

$c=array_combine($fname,$age);
print_r($c);

The array_combine() function creates an array by using the elements from one "keys"
array and one "values" array.
Note: Both arrays must have equal number of elements!
ARRAYS- Functions For Arrays
array_count_values()

<?php

$a=array("A","Cat","Dog","A","Dog");

print_r(array_count_values($a));

?>

The array_count_values() function counts all the values of an array


ARRAYS- Functions For Arrays
array_diff()

$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("e"=>"red","f"=>"green","g"=>"blue");

$result=array_diff($a1,$a2);
print_r($result);

The array_diff() function compares the values of two (or more) arrays, and returns
the differences.
This function compares the values of two (or more) arrays, and return an array that
contains the entries from array1 that are not present in array2 or array3, etc
array_fill()
ARRAYS- Functions For Arrays
The array_fill() function fills an array with values
Syntax : array_fill(index,number,value)

$a1=array_fill(0,4,"blue");
print_r($a1);
echo "<br>";

$b1=array_fill(0,1,array(“red”,”blue”));
print_r($b1);

Output:
array_flip()
ARRAYS- Functions For Arrays
Flip all keys with their associated values in an array

<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");

$result=array_flip($a1);

print_r($result);
?>
array_key_exists()
ARRAYS- Functions For Arrays
Check if the key exists in an array

<?php
$a=array(“ali"=>“100",“taha"=>“200");
if (array_key_exists("ali",$a))
{
echo "Key exists!";
}
else
{
echo "Key does not exist!";
}
?>
array_keys()
ARRAYS- Functions For Arrays
Return an array containing the keys

<?php

$a=array(“a"=>“ali",“b"=>“hamza",“c"=>“taha");

print_r(array_keys($a));

?>
array_map()
ARRAYS- Functions For Arrays
Send each value of an array to a function, multiply each value by itself, and return an array with the new
values

<?php

function myfunction($v)
{
return($v*$v);
}

$a=array(1,7,3,4,9);

print_r(array_map("myfunction",$a));

?>
array_merge()
ARRAYS- Functions For Arrays
Merge two arrays into one array

<?php

$a1=array("red","green");

$a2=array("blue","yellow");

print_r(array_merge($a1,$a2));

?>
array_multisort()
ARRAYS- Functions For Arrays
Return a sorted array in ascending order

<?php
$a=array("Dog","Cat","Horse","Bear","Zebra");

array_multisort($a);

print_r($a);

?>
array_search()
ARRAYS- Functions For Arrays
Search an array for the value "red" and return its key:

array_search(value, array,)

<?php
$a=array("a"=>"red","b"=>"green","c"=>"blue");

echo array_search("red",$a);

?>
Returns the key of a value if it is found in the array, and FALSE otherwise. If the value
is found in the array more than once, the first matching key is returned.
array_pop()
ARRAYS- Functions For Arrays
Delete the last element of an array

<?php

$a=array("red","green","blue");

array_pop($a);

print_r($a);

?>
Unset
ARRAYS- Functions For Arrays
Delete the element of an array

<?php
$delete_item = ' friday';
$months = array(‘monday', ‘tuesday', ‘wednesday', ‘thursday', ‘friday’);
if (($key = array_search($delete_item, $months)) !== false)
{
unset($months[$key]);
}
?>
array_push()
ARRAYS- Functions For Arrays
Insert "blue" and "yellow" to the end of an array

<?php

$a=array("red","green");

array_push($a,"blue","yellow");

print_r($a);

?>
array_rand()
ARRAYS- Functions For Arrays
Return an array of random keys

<?php
$a=array("red","green","blue","yellow","brown");

$random_keys=array_rand($a,3);

echo $a[$random_keys[0]]."<br>";

echo $a[$random_keys[1]]."<br>";

echo $a[$random_keys[2]];

?>
array_replace()
ARRAYS- Functions For Arrays
Replace the values of the first array ($a1) with the values
from the second array ($a2):

<?php

$a1=array("red","green");

$a2=array("blue","yellow");

print_r(array_replace($a1,$a2));

?>
array_reverse()
ARRAYS- Functions For Arrays
Return an array in the reverse order
<?php

$a=array("a"=>"Volvo","b"=>"BMW","c"=>"Toyota");

print_r(array_reverse($a));

?>
Example1:
ARRAYS- Functions For Arrays

What will be the output of the following PHP code?

$fruits = array ("mango", "apple", "pear", "peach");


$fruits = array_flip($fruits);
echo ($fruits[0]);
Example2:
ARRAYS- Functions For Arrays

You need to write a program in PHP to remove specific element by value from an array using PHP program.

Instructions:

Take an array with list of month names.


Take a variable with the name of value to be deleted.
You can use PHP array functions or foreach loop.
Example2:
ARRAYS- Functions For Arrays

You need to write a program in PHP to remove specific element by value from an array using PHP program.
Solution:
$delete_item = 'march'; // take a list of months in an array
$months = array('jan', 'feb', 'march', 'april', 'may’);
if (($key = array_search($delete_item, $months)) !== false)
{
unset($months[$key]);
}
Example3:
ARRAYS- Functions For Arrays

$color = array('white', 'green', 'red', 'blue', 'black’);

Write a script which will display the following string :

I like green color but my brother like red and


blue color.
The black absorbs more heat then white.
ARRAYS
Example4:

Suppose we have following data of array:

78, 60, 62, 68, 71, 68, 73, 85, 66, 64, 76, 63, 75, 76, 73, 68, 62, 73, 72, 65, 74, 62, 62, 65, 64, 68, 73, 75,
79, 73

Write array program to output following from above array


ARRAYS- Sort Functions For Arrays
$temp_array = array(78,60,62,68,71,68,73,85,66,64,76,63,81,76,73,68,72,73,75,65,74,63,67,65,64,68,73,75,79,73);

$tot_temp = 0;

$temp_array_length = count($temp_array);

foreach($temp_array as $temp) {

$tot_temp += $temp; }

$avg_high_temp = $tot_temp/$temp_array_length;

echo "Average Temperature is : ".$avg_high_temp." "; sort($temp_array); echo " List of five lowest temperatures :";

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

echo $temp_array[$i].", ";

echo "List of five highest temperatures :";

for ($i=($temp_array_length-5); $i< ($temp_array_length); $i++) {

echo $temp_array[$i].", ";

You might also like