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

Subject

Obtained Marks

Total Marks

Percentage

English Grammar

63

80

78.75%

Mathematics

70

80

87.5%

Geography

52

80

65%

Science

59

80

73.75%

History

69

80

86.25%

Economics

77

80

96.25%

Art

55

80

68.75%

Music

66

80

82.5%

Total

511

640

79.84%

 


Code:

//code before <html>

<?php

    $fname = "Peter";

    $lname = "Watson";

    $dob = "16-07-2001";

    $roll_no = 21;


    $student_marks = array(

                array("subject"=>"English Grammar","obtained_marks"=>63,"total_marks"=>80),

                array("subject"=>"Mathematics","obtained_marks"=>70,"total_marks"=>80),

                array("subject"=>"Geography","obtained_marks"=>52,"total_marks"=>80),

                array("subject"=>"Science","obtained_marks"=>59,"total_marks"=>80),

                array("subject"=>"History","obtained_marks"=>69,"total_marks"=>80),

                array("subject"=>"Economics","obtained_marks"=>77,"total_marks"=>80),

                array("subject"=>"Art","obtained_marks"=>55,"total_marks"=>80),

                array("subject"=>"Music","obtained_marks"=>66,"total_marks"=>80),

    );

?>


//code inside <body>

<img src="images/profile_photo.png" >

      <br />

      <?php

         echo "Name: " . $fname ." ". $lname . "<br />";

         echo "Date of birth: " . $dob . "<br />";

         echo "age: " . date_diff(date_create($dob),date_create(date("Y/m/d")))->format("%Y")."<br />";

         echo "Roll no: " . $roll_no."<br />"."<br />";

       ?>

       <table>

          <tr> <th>Sr.no</th> <th>Subject</th> <th>Obtained Marks</th> <th>Total Marks</th> <th>Percentage</th> </tr>

          <?php

      $i = 1;

      $total_obtained_marks = null;

      $total_marks = null;

      foreach($student_marks as $marks){

          echo "<tr><td>".$i."</td><td>".$marks["subject"]."</td><td>".$marks["obtained_marks"]."</td>

                <td>".$marks["total_marks"]."</td>

                <td>".round(($marks["obtained_marks"]*100)/$marks["total_marks"],2)."%"."</td></tr>";

 

   $total_obtained_marks += $marks["obtained_marks"];

   $total_marks += $marks["total_marks"];

   $i++;

             }

           echo "<tr><td></td><td>Total</td><td>$total_obtained_marks</td><td>$total_marks</td>

           <td>".round(($total_obtained_marks*100)/$total_marks,2)."%"."</td></tr>";

?>

</table>


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 


Month

Present days

Absent days

Total days

Obtained Marks

June

13

7

20

1.3

July

16

4

20

1.6

August

11

9

20

1.1

september

20

0

20

2

October

19

1

20

1.9

November

12

8

20

1.2

December

15

5

20

1.5

January

8

12

20

0.8

February

14

6

20

1.4

March

17

3

20

1.7

Total

145

55

200

14.5





code:

//before <html>

<?php

   $attendance_records = array(

   array("month"=>"June","present_days"=>13,"total_days"=>20),

   array("month"=>"July","present_days"=>16,"total_days"=>20),

   array("month"=>"August","present_days"=>11,"total_days"=>20),

   array("month"=>"september","present_days"=>20,"total_days"=>20),

   array("month"=>"October","present_days"=>19,"total_days"=>20),

   array("month"=>"November","present_days"=>12,"total_days"=>20),

   array("month"=>"December","present_days"=>15,"total_days"=>20),

   array("month"=>"January","present_days"=>8,"total_days"=>20),

   array("month"=>"February","present_days"=>14,"total_days"=>20),

   array("month"=>"March","present_days"=>17,"total_days"=>20)

   );

?>


//inside <body>

<h3>Attendance record</h3>   

    <table>

     <tr> <th>Month</th> <th>Present days</th> <th>Absent days</th> <th>Total days</th> <th>Obtained Marks</th> </tr>

     <?php

   $total_present_days = null;

   $total_absent_days = null;

   $total_days = null;

   $total_marks = null;

  

         for($i = 0; $i<count($atendance_records); $i++){

             echo "<tr><td>" . $attendance_records[$i]["month"] ."</td>

                  <td>" . $attendance_records[$i]["present_days"] . "</td> 

                  <td>" . ($atendance_records[$i]["total_days"] - $atendance_records[$i]["present_days"]) ."</td>

             <td>" .$attendance_records[$i]["total_days"]. "</td><td>". $atendance_records[$i]["present_days"]/10.

                  "</td></tr>";

          

             $total_present_days += $atendance_records[$i]["present_days"];

             $total_absent_days += $atendance_records[$i]["total_days"]-$atendance_records[$i]["present_days"];

             $total_days += $atendance_records[$i]["total_days"];

             $total_marks += $atendance_records[$i]["present_days"]/10;

         }

     echo "<tr class='bold'><td>Total</td><td> $total_present_days </td><td> $total_absent_days </td><td> $total_days </td><td> $total_marks </td></tr>";

?>

</table>






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:

<?php

    $index = 0;

    $computers = array(

        "computer_1" => array("ram"=>4, "processor"=>"i3", "company"=>"Arm", "status"=>"working"),

        "computer_2" => array("ram"=>32, "processor"=>"A7", "company"=>"Apple", "status"=>"working"),

        "computer_3" => array("ram"=>8, "processor"=>"i5", "company"=>"Hitachi", "status"=>"not-working"),

        "computer_4" => array("ram"=>16, "processor"=>"i7", "company"=>"IBM", "status"=>"not-working"),

        "computer_5" => array("ram"=>64, "processor"=>"i11", "company"=>"Nvidia", "status"=>"working"),

        "computer_6" => array("ram"=>48, "processor"=>"i10", "company"=>"Qualcomm", "status"=>"working"),

        "computer_7" => array("ram"=>12, "processor"=>"i5", "company"=>"Rockchip", "status"=>"not-working"),

        "computer_8" => array("ram"=>24, "processor"=>"i7", "company"=>"Samsung", "status"=>"working")

    );


    foreach($computers as $key => $com)

    {

        if($com["status"] == "not-working")

        {

            $faulty_computers[$key] = $com;

            array_splice($computers,$index,1);

            $index++;

        }

  }


$faulty_comp_sentence = null;

    foreach($faulty_computers as $key => $faulty_comps)

    {

      $faulty_comp_sentence = $faulty_comp_sentence . $key . ", ";

    }

    $faulty_comp_sentence = rtrim($faulty_comp_sentence, ", ") . " are not working";

    echo $faulty_comp_sentence;

?>


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


<?php

    $cars = array(

   array("company"=>"Skoda", "model"=>"Octavia", "engine"=>"1984 cc", "type"=>"Sedan"),

   array("company"=>"Land Rover", "model"=>"Discovery", "engine"=>"1999 cc", "type"=>"SUV"),

   array("company"=>"Audi", "model"=>"A4", "engine"=>"1998 cc,", "type"=>"Sedan"),

   array("company"=>"Audi", "model"=>"Q2", "engine"=>"1984 cc", "type"=>"SUV"),

   array("company"=>"Land Rover", "model"=>"Range Rover Sport", "engine"=>"1997 cc", "type"=>"SUV"),

   array("company"=>"Jaguar", "model"=>"F-TYPE", "engine"=>"1997 cc", "type"=>"Coupe"),

   array("company"=>"Skoda", "model"=>"Superb", "engine"=>"1984 cc", "type"=>"Sedan"),

   array("company"=>"Audi", "model"=>"Q8", "engine"=>"2995 cc", "type"=>"SUV"),

   array("company"=>"Land Rover", "model"=>"Range Rover Evoque", "engine"=>"2000 cc", "type"=>"SUV"),

   array("company"=>"Jaguar", "model"=>"XF", "engine"=>"1997 cc", "type"=>"Sedan"),

   array("company"=>"Skoda", "model"=>"Rapid", "engine"=>"999 cc", "type"=>"Sedan"),

   array("company"=>"Jaguar", "model"=>"F-Pace", "engine"=>"1997 cc", "type"=>"SUV"),

   array("company"=>"Land Rover", "model"=>"Velar", "engine"=>"1997 cc", "type"=>"SUV"),

   array("company"=>"Land Rover", "model"=>"Defender", "engine"=>"1997 cc", "type"=>"SUV"),

   array("company"=>"Audi", "model"=>"A6", "engine"=>"1984 cc", "type"=>"sedan"),


    );

    foreach($cars as $car)

    {

   switch($car["company"])

   {

   case "Skoda":

   $skoda[] = $car;

   break;

  

   case "Land Rover":

   $land_rover[] = $car;

   break;

  

   case "Audi":

   $audi[] = $car;

   break;

  

   case "Jaguar":

   $jaguar[] = $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



//before <html>

<?php include "example4-a.php"; ?>


//inside <body>

<table>

   <tr> <th>Sr. no.</th> <th>Skoda</th> <th>Audi</th> <th>Land Rover</th> <th>Jaguar</th> </tr>

   </ol>

   <?php

   for($i=0; $i<count($cars); $i++){

      if(isset($skoda[$i]) or isset($land_rover[$i]) or isset($audi[$i]) or isset($jaguar[$i])){

     echo"<tr>";

  

     echo"<td>" . ($i+1) . "</td>";

  

     if(isset($skoda[$i])){

     echo "<td>" . $skoda[$i]["model"] . "</td>";

     }

     else{echo "<td></td>";}

  

     if(isset($audi[$i])){

     echo "<td>" . $audi[$i]["model"] . "</td>";

     }

     else{echo "<td></td>";}

  

     if(isset($land_rover[$i])){

     echo "<td>" . $land_rover[$i]["model"] . "</td>";

     }

     else{echo "<td></td>";}

  

     if(isset($jaguar[$i])){

     echo "<td>" . $jaguar[$i]["model"] . "</td>";

     }

     else{echo "<td></td>";}

  

     echo"</tr>";

     }

     else{break;}

     }

   ?>

</table>



output:

Sr. no.

Skoda

Audi

Land Rover

Jaguar

1

Octavia

A4

Discovery

F-TYPE

2

Superb

Q2

Range Rover Sport

XF

3

Rapid

Q8

Range Rover Evoque

F-Pace

4


A6

Velar


5



Defender


 


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.

//before <html>

<?php

            $customers = array(

                array("name"=>"Emily", "subscription"=>"yearly", "request"=>"no"),

                array("name"=>"jack", "subscription"=>"yearly", "request"=>"yes"),

                array("name"=>"Mark", "subscription"=>"monthly", "request"=>"yes"),

                array("name"=>"Johnny", "subscription"=>"monthly", "request"=>"no"),

                array("name"=>"Chris", "subscription"=>"yearly", "request"=>"yes"),

                array("name"=>"Harry", "subscription"=>"yearly", "request"=>"yes"),

                array("name"=>"Larry", "subscription"=>"monthly", "request"=>"yes"),

                array("name"=>"Megan", "subscription"=>"yearly", "request"=>"no"),

                array("name"=>"Rusty", "subscription"=>"monthly", "request"=>"no"),

                array("name"=>"Stanley", "subscription"=>"yearly", "request"=>"yes")

                );


            foreach($customers as $customer)

{   

                if ($customer["subscription"] == "yearly" and $customer["request"] == "yes")

                {

                    $receivers[] = $customer["name"];

                }

            }

//inside <body>           

            echo "</h3>The following customers will receive a special book every month</h3>";

            echo "<ol>";

            foreach($receivers as $receiver)

            {

                echo "<li>". $receiver . "</li>";

            }

            echo "</ol>";

?>




output:

The following customers will receive a special book every month

  1. jack

  2. Chris

  3. Harry

  4. 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.



<?php

    $animals = array(

   "dog" => array(2, 2, 4, 3, 9, 1, 3, 4),

   "cat" => array(6, 6, 12, 5, 10, 5, 3, 1, 12, 1),

   "goat" => array(8, 10, 5, 3, 6, 10, 15, 2, 12, 3, 4, 5),

   "cow" => array(2, 14, 20, 2, 21, 6, 10, 14, 4, 12, 20, 6, 9),

   "sheep" => array(3, 2, 2, 10, 10, 5, 3, 11, 9, 4, 5, 9)

);


    echo "Average age of animals are given below" . "<br /><br />";

    foreach($animals as $key => $ani)

    {

     $animals[$key]["avrage_age"] = round(array_sum($ani) / count($ani));

     echo ucwords($key) . ": " . $animals[$key]["avrage_age"] . "<br />";

    }

?>



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 



<?php

    $employees = array(

   array("name"=>"Vaneet","salary"=>25000),

   array("name"=>"Shivani","salary"=>18000),

   array("name"=>"Tara","salary"=>22000),

   array("name"=>"Darshan","salary"=>16000),

   array("name"=>"Sudhir","salary"=>10000),

   array("name"=>"Vishal","salary"=>30000)

    );

    for($i=0; $i<count($employees); $i++)

    {

   $employees[$i]["tds"] = ($employees[$i]["salary"] * 10) / 100;

   $employees[$i]["net_salary"] = $employees[$i]["salary"] - $employees[$i]["tds"];

    }

print_r($employees);


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>

<?php

foreach($classes as $class => $students){

echo "<h3>Class ".$class."</h3><table class='table'><thead><tr><th>First Name</th><th>Last Name</th><th>Marks</th> 

      <th>Age</th></tr></thead><tbody>";

foreach($students as $student){

echo "<tr><td>".$student["fname"]."</td><td>".$student["lname"]."</td><td>".$student["marks"]."</td><td>".

            $student["age"]."</td></tr>";

}

      echo "</tbody></table> <br /><br /><br /><br />";

}

?>

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.

//$products filtration. before <html>

$categories = array("CPU","RAM","peripherals","mother-board","storage");//used to print category dropdown

$filters = null;

foreach($_POST as $field => $field_val){

if($field_val != ""){

$filters[$field] = $field_val;

}

}

$products = filter_products($filters, $products);


//filter form. inside <body> and Before <table>

<form class="row" method="POST" action="you_file.php">

   <div class="col-auto"><label>Filters:</label></div>

   <div class="col-auto"><input type="text" class="form-control" placeholder="Product name" name="product_name"/> 

   </div>

   <div class="col-auto"><input type="number" class="form-control" placeholder="price" min="0" name="price"/></div>

<div class="col-auto">

<select class="form-select" name="category">

  <option value="" selected>Category</option>

  <?php

  foreach($categories as $cat){

      echo "<option value='".$cat."'>".$cat."</option>";

  }

  ?>

</select>

      </div>

   <div class="col-auto"><button type="submit" class="btn btn-secondary">Submit</button></div>

</form>

<!-- HTML table below -->


  • $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 !!!