php 7.2
Example 1:
Given below is an email of a student’s result
Name: Peter Watson
Date of birth: 16-07-2001
age: 19
Roll no: 21
Code:
Explanation:
Four variables (fname, name, dob, roll_no) are initiated and assigned to (“Peter”,“Watson”,“16-07-2001”,21) respectively.
A variable $student_marks is initiated and assigned to an array which contains the “subject name”, “obtained marks” and “total marks” of each subject.
First the $fname, $lname, age, roll no and the profile picture is printed.
In the <th> tags the table headings are written.
The variables $total_obtained_marks and $total_marks are assigned to null. This is done because the variables must be initiated before using them. $i is used for the serial number. It’s incremented by 1 on each iteration, at the end of the loop
In the foreach loop, each iteration prints the values of one sub-array as a row in the <td> tags. Notice: the serial number is printed the first <td>.
The percentage is calculated by using the basic math formula: 2 as a percentage of 10 = (2 x 10)/100 = 20/100 = 20%. It is rounded of to two decimals using the round() function
On each iteration of the foreach loop the value of $marks["obtained_marks"] and $marks["total_marks"] will be added to $total_obtained_marks and $total_marks respectively. At the end of the loop $total_obtained_marks and $total_marks will contain the total obtained marks and total marks.
After the loop the last row of the table is printed, which contains the total of all columns.
Example 2:
Given below is the attendance record of a student. Each month there are 20 lectures.The marks are given depending on the number of lectures the student has attended. If all the lectures are attended, the student will get 2 marks.
e.g. if 10 lectures are attended the student will get 1 mark, if 8 lectures are attended the student will get 0.8 marks.
Attendance record
code:
Explanation:
A variable $attendance_records is declared and assigned to a multidimensional array. Each sub-array contains the month name, present
days and total days of each month.
In the <h3> tag the heading is written “Attendance record”
In the <th> tags the table headings are written
Four variables are declared ($total_present_days, $total_absent_days, $total_days, $total_marks) and assigned to null.
In the for loop
Each iteration prints all the values from one sub-array. The absent days are calculated by doing (total days - present days). The marks are calculated using this formula (present days ÷ 10).
In each iteration the present days, absent days, total days and total marks are added into $total_present_days, $total_absent_days $total_days and $total_marks respectively.
The variables $total_present_days, $total_absent_days $total_days and $total_marks are printed as the last row of the table outside the loop.
Example 3:
In a cyber café there are 8 computers and some of them aren't working. The list of computers is stored in an array. The computers which aren’t working are moved to a new array $faulty_computers. At the end the computers which are not working are printed.
code:
output:
computer_3, computer_4 and computer_7 are not working
explanation:
In the first foreach the computers which aren't working are moved
The if condition checks if the status is “not-working”, if true that sub-array will be inserted in $faulty_computers on the same index using $key.
Then the sub-array will be removed from $computers using array_splice(). array_splice() needs the numeric index of an element to remove it, therefore $index is used. $index is assigned to 0 on the second line and is incremented by one on each iteration. Like this $index contains the numeric key of the current sub-array even though the sub-arrays have string indexes.
The second foreach is used to make a sentence string of the faulty computers.
$faulty_comp_sentence is set to null before the loop because it would get concatenated before being declared
The computer names are stored as keys, so $key must be used.
The computer name ($key) with a comma is concatenated to $faulty_comp_sentence which is reassigned to $faulty_comp_sentence
Like this at the end of the loop, $faulty_comp_sentence will contain all the faulty computers string, separated by commas.
Example 4-a:
There is an array $cars containing car data of multiple cars. The cars given are from only four companies. This data must be sorted by company in separate arrays. Each sub-array contains the data of one car
Explanation:
In the switch() the company name of the current sub-array is passed. In each case a company name is written. When a case is matched, the current sub-array will be inserted in a new array on a dynamic key. The new array will have the same name as the sub-array’s company.
Example 4-b:
In this example the data sorted in the four arrays in the last example will be printed in an html table. The include method is used so that we can use the arrays from another file. Basically, include just copies the code from the given path and will paste it on the point where you have written the include method (the file name of “Example 4-a” is example4-a.php. example4-b.php is the current file. example4-a.php and example4-b.php are in the same folder). The isset() function is also used to check if a variable is initiated or not.
Reference link include: https://www.w3schools.com/php/php_includes.asp
Reference link isset: https://www.w3schools.com/php/func_var_isset.asp
output:
Explanation:
The for loop itraitrates based on $cars because the company arrays contain different amounts of elements. The number of elements in $cars are greater than any company array, so any elements won’t get left out
In the for loop, the first if condition checks
whether the sub-array from any of the company-array is initiated or not.
Four isset() functions are passed which are separated by or. In each isset() the sub-array of a company is passed dynamically using $i.
If 1 or more isset() returns true, the if statement will execute, else the loop will break;
Inside the if statement code
The <tr> tag is opened
In the first <td> the serial number is printed using $i. $i is added 1 because $i starts from 0, but we want it to start from 1.
Four if conditions are written. Each if condition checks if there is a sub-array initiated on the $i index from one company array. If satisfied, it will print the model from that subarray in the <td>, else it will print an empty <td>
The <tr> tag is closed
Example 5:
A newspaper press gives a special book to customers who have paid a yearly subscription and want it. $customers is an array containing the customers list. Each sub-array contains one customer’s data. The customers who will get the book are added in a separate array.
output:
The following customers will receive a special book every month
jack
Chris
Harry
Stanley
Explanation:
The first for loop is used to insert eligible customers in a new array
The if condition checks whether subscription = “yearly” and request = “yes”. If satisfied, it will insert the current sub-array in $receivers on a dynamic index.
The second for lupus used to print the list of receivers.
The <ul> tag is opened before the loop and closed outside the loop.
The echo statement will print one receiver every iteration dynamically using $i. The receiver names are printed between the <li> tag.
Example 6:
In a farm there are a lot of animals. The average age of each type of animal must be calculated. $animals is an array containing the animal ages.
Each sub-array contains the ages of one type of animal.
The array_sum() function is used to get the sum of ages.
output:
Average age of animals are given below
Dog: 4
Cat: 6
Goat: 7
Cow: 11
Sheep: 6
Explanation:
In the loop the average age is calculated and inserted in the same sub-array on the key "avrage_age". Average age is calculated by dividing the sum of all ages by the count of all ages. ucwords() capitalizes case (makes the first letter of all words capital)
Example 7:
$employees contains the list of employees in an office. Each sub-array has the name and salary of 1 employee. The tds and net salary of each employee must be calculated. The net salary means the salary remaining after the tds has been subtracted from the whole salary. The tds is 10% of the whole salary
output:
Array ( [0] => Array ( [name] => Vaneet [salary] => 25000 [tds] => 2500 [net_salary] => 22500 )
[1] => Array ( [name] => Shivani [salary] => 18000 [tds] => 1800 [net_salary] => 16200 )
[2] => Array ( [name] => Tara [salary] => 22000 [tds] => 2200 [net_salary] => 19800 )
[3] => Array ( [name] => Darshan [salary] => 16000 [tds] => 1600 [net_salary] => 14400 )
[4] => Array ( [name] => Sudhir [salary] => 10000 [tds] => 1000 [net_salary] => 9000 )
[5] => Array ( [name] => Vishal [salary] => 30000 [tds] => 3000 [net_salary] => 27000 ) )
Explanation:
In the for loop, on each iteration the tds and net salary of 1 sub-array is calculated and inserted as new fields in the same sub-array.
As you can see in the output, the tds and net salary have been inserted as new fields in each sub-array. The new fields are highlighted in blue.
Example 8: based on “4 - Custom functions/example 7”. $classes returned from allocate_class() is used to print separate tables for each class. $classes are defined before <html>. Given below is the code inside <body>
The outer loop iterates the classes, and the nested loop iterates the students inside the class. Notice the tags printed before and after the nested loop. The nested loop just prints the rows inside <tbody>, the remaining tags are printed in the main loop (like: <table>, <thead>, <tbody> etc…). As you know, $classes stores the classname as the key of that subarray. That key is printed as the table heading
The output should be four separate tables, each for a class. Exercise: use ksort() to sort $classes (so you will get the classes in an alphabetical order)
Example 9: before going ahead, you must know about the $_POST variable. It basically contains the posted (submitted) values of a form. The values are indexed by the name used in the input field. This example uses $products and filter_products() from “4 - Custom functions/example 6b”
You will see a form above a product table that filters the records. Note: $products, filter_products() and $categories are defined before <html>. Only the snippets of “$products filtarisation” and the “filter form” are given.
$filters is populated using the post values. $filters is set to null because if no filters are inserted, $filters won’t be defined, and an error will
occur while passing it in filter_products()
$_POST is looped so we get every value. The value is checked to be (!= “”). When a blank field is submitted, it has a value of “”
While the value is inserted in $filters, the same key is used. (the same keys is used in $products, filter_products() and the name of inputs )
filter_products() is called, and the filtered array is reassigned to $products. The HTML table can now be populated using $products
Now you have a fully functional filters !!!