Week 03 Lec 01 Arrays
Week 03 Lec 01 Arrays
02
SADAM HUSSAIN
Exercise
1. Answer
for($x=1;$x<=5;$x++)
for ($y=1;$y<=$x;$y++)
echo "*";
if($y< $x)
echo "\n";
}
While Loop statement
Example practice:
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:
$num = 3;
$factorial = 1;
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;
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
<?php
$i = 0
do
{
print "hi";
$i++;
}
while ($i != 3);
?>
Do…While Loop statement
<?php
$i = 0
while ($i < 3)
{
print "hi";
$i--;
}
print "hello"
?>
Do…While Loop statement
<?php
$i = "";
while($i)
{
print "hi";
}
print "hello";
?>
PHP Functions
Syntax
function functionName() {
code to be executed;
}
PHP Functions
<?php
function abc() {
echo "Hello world!";
}
Ex1:
function abc($fname) {
echo "$fname.<br>";
}
abc(“ali");
abc(“hamza");
Ex2:
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");
Ex1:
declare(strict_types=1); // strict requirement
// 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
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;
}
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:
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.
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] . ".";
or:
$age['ali'] = "35";
$age[‘taha'] = "37";
$age[‘hamza'] = "43";
$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
the key
ARRAYS- Sort Functions For Arrays
count($age);
ARRAYS- Functions For Arrays
Lets take array:
$age=array(“taha"=>"35",“hamza"=>"37",“ali"=>"43");
array_change_key_case() :
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',
)
);
$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));
?>
$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
You need to write a program in PHP to remove specific element by value from an array using PHP program.
Instructions:
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
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
$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 :";