Share
Web Development

Course Outline

Week 1
Week 2
Week 3
  • Arrays
  • Constants and Global Variables
  • Functions
Week 4
Week 5
Week 6

SponsoredAdvertise

Explanations to week content

Arrays

A data structure that stores a set of values. Each value has an index that you can use to access it.


Declaring An Array


Syntax:

$variableName = array();

The above syntax declares a variable which is an arrayvariable.


Storing A Value In An Array To An Index

$variableName[indexToInsertTheValueInto] =value_to_insert;

Array index starts from 0.


Example

The following PHP script declares a student_namesarray and insert names into that array

<?php
$student_names = array();
$student_names[0] = "Adjei";
$student_names[1] = "Kofi";
$student_names[2] = "Ama";
$student_names[3] = "Bortey";
$student_names[4] = "Adjoa";
?>

 

Explanation

the array(); indicates that the variable$student_names is an array variable

$student_names[0] = "Adjei";

 Stores the name Adjei into the variable atindex 0

 $student_names[1] = "Kofi";

 Stores the name Kofi into the variable at index1

 and so on.

 

SyntaxIndexValue At Index
$student_names[0] = "Adjei";0Adjei
$student_names[1] = "Kofi";1Kofi
$student_names[2] = "Ama";2Ama
$student_names[3] = "Bortey";3Bortey
$student_names[4] = "Adjoa";4Adjoa


Storing a value to an array using the array_push function


Syntax:


array_push($arrayVariableName,$value);


Example


To add another name to the array after the last indexof the array, we can use the syntax below:

array_push($student_names,”Mariamatu”);

array_push($student_names,”Abena”);


ACCESSING THE VALUE OF AN ARRAY


You access a single array content by the index of thearray. For instance if we want to access the name in the 2 index (position3) we can use the syntax:

$name = $student_names[2]; //This will accessthe value stored in index 2 and assign the value to $name

echo $student_names[2]; //This will print out the namestored in the array at index 2


ACCESSING ALL THE CONTENT OF AN ARRAY


Array contents can be accessed in two ways:

1.    Using a for loop

2.    Using a foreach



USING A FOR LOOP


In order to get the content of the array, you will need to know the total items in the array so that you can iterate from 0 to(items in array - 1).

The iteration will be less because the index starts from 0

To get the total items in an array the syntax is used:

count($arrayVariableName);

Thus to get the total items in the $student_names  array, the syntax below can be used:

$total = count($student_names);

The content in the array can now be accessed as:

for($i=0;$i<$total;$i++){
    echo “<p>”.$student_names[$i].”</p>”;
}


Explanation


$total = count($student_names);

The value of $total will be 5 since there arefive items in the $student_names array

We then iterate from 0 to 4 when theloop ends at the point $i is 5

IterationValue of $iAccessing Content of ArrayContent
1$i = 0$student_names[0]Adjei
2$i = 1$student_names[1]Kofi
3$i = 2$student_names[2]Ama
4$i = 3$student_names[3]Bortey
5$i = 4$student_names[4]Adjoa
6$i = 5Loop ends 

 


USING FOREACH


The foreach is also used for arrays with a key and value.

Syntax:

foreach($nameOfArray as $variableNameToAccessArrayContent){

            //Use the $variableNameToAccessArrayContent by their keys

}

Thus the array $student_names can also be accessed as:

foreach($student_names as $name){
    echo “<p>”.$name.”</p>”;
}


ILLUSTRATION


Create a file name array_example_1.php . Type the code below and run to demonstrate how the array works. Add more entries to the array and modify the for loop accessing the array and run the script any time you make changes to the script.

<?php
//Declare the array variable
$student_names = array();
//Store values in the array
$student_names[0] = "Adjei";
$student_names[1] = "Kofi";
$student_names[2] = "Ama";
$student_names[3] = "Bortey";
$student_names[4] = "Adjoa";
//Storing values to array using array_push
array_push($student_names,"Mariamatu");
array_push($student_names,"Abena");
//Access the value stored in index 2 and assign the value to $name
$name = $student_names[2];
echo "<p>Name at index 2 is: ".$name."</p>";
echo "<p>Name at index 2 is: ".$student_names[2]."</p>";
/* Display the entire array content */
/* Get the total number of items in the array */
$total = count($student_names);
/* Loop through each array index */
for($i=0;$i<$total;$i++){
    echo "<p>".$student_names[$i]."</p>";
}
/* Using a foreach approach */
foreach($student_names as $name){
    echo "<p>".$name."</p>";
}

?>


ARRAYS WITH MULTIPLE FIELDS

You can write an array which has a key and its value.


Thus:

arrayName[key] = value;

The values are accessedusing the keys.


Example


<?php
$person = array();
$person['firstname'] = "Godwin";
$person['lastname'] = "Ashong";
$person['nationality'] = "Ghanaian";
$person['hometown'] = "Teshie";
echo "First Name:".$person['firstname']." Last Name:".$person['lastname']." Nationality:".$person['nationality']." Home Town:".$person['hometown'];
?>


ARRAYS IN AN ARRAY

You can store arrays in another array and fetch each of the arrays using the foreach loop and access each array values using the key.


Example


<?php
$person = array();
$person['firstname'] = "Godwin";
$person['lastname'] = "Ashong";
$person['nationality'] = "Ghanaian";
$person['hometown'] = "Teshie";
$people = array();
array_push($people,$person);
$person['firstname'] = "Joseph";
$person['lastname'] = "Agya";
$person['nationality'] = "Ghanaian";
$person['hometown'] = "Nungua";
array_push($people,$person);
foreach($people as $person){
    echo "<p>First Name:".$person['firstname']." Last Name:".$person['lastname']." Nationality:".$person['nationality']." Home Town:".$person['hometown']."</p>";
}
?>

In an actual production, each of the arrays will be rows of a database and these rows stored in another array which is fetched at the front end to be displayed,

So there could be a database which has rows of person details. So these information can be fetched and displayed in a table.

CODING STYLES

 

NO MATTER WHAT YOUR PROFICIENCY LEVEL in PHP, no matter how familiar you are with the language internals or theidiosyncrasies of various functions or syntaxes, it is easy to write sloppy orobfuscated code. Hard-to-read code is difficult to maintain and debug. Poor codingstyle connotes a lack of professionalism.

 

If you were to stay at a job the rest of your life andno one else had to maintain your code, it would still not be acceptable towrite poorly structured code. Troubleshooting written  two or more years ago is difficult, even whenthe style is clean. When you stray into code that is authored in poor style, itoften takes as long to figure out the logic as it would to have just re implementedthe library from scratch.

 

To complicate matters, none of us code in a vacuum.Our code needs to be maintained by our current and future peers. The union oftwo styles that are independently readable can be as unreadable andunmaintainable as if there were no style guide at all.

 

Therefore, it is important not only that we use astyle that is readable, but that we use a style that is consistent across allthe developers working together

 

Indentation

 

The importance of indentation for code organizationcannot be exaggerated. Many programmers consider it such a necessity that thePython scripting language actually uses indentation as syntax; if Python codeis not correctly indented, the program will not parse!

 

Although indentation is not mandatory in PHP, it is apowerful visual organization tool that you should always consistently apply tocode.

Consider the following code:

 

if($month == ‘september’ || $month == ‘april’ || $month== ‘june’ || $month ==
‘november’) { return 30;
}
else if($month == ‘february’) {
if((($year % 4 == 0) && !($year % 100)) ||($year % 400 == 0)) {
return 29;
}
else {
return 28;
}
}
else {
return 31;
}

 

Compare that with the following block that is identical except for indentation:

 

if($month == ‘september’ ||
$month == ‘april’ ||
$month == ‘june’ ||
$month == ‘november’) {
return 30;
}
else if($month == ‘february’) {
if((($year % 4 == 0) && ($year % 100)) ||($year % 400 == 0)) {
return 29;
}
else {
return 28;
}
}
else {
return 31;
}

 

 

In the latter version of this code, it is easier todistinguish the flow of logic than in the first version.

 

When you’re using tabs to indent code, you need tomake a consistent decision about whether the tabs are hard or soft. Hard tabsare regular tabs. Soft tabs are not really tabs at all; each soft tab isactually represented by a certain number of regular spaces. The benefit ofusing soft tabs is that they always appear the same, regardless of the editor’stab-spacing setting. It is preferred to use soft tabs. With soft tabs set andenforced, it is easy to maintain consistent indentation and whitespacetreatment throughout code. When you use hard tabs, especially if there aremultiple developers using different editors, it is very easy for mixed levelsof indentation to be introduced.

 

Constants and Global Variables

 

As the name suggests, constants are PHP containers forvalues that remain constant and never change. They’re mostly used for data thatis known well in advance and that is used, unchanged, in multiple places withinyour application. Good candidates for constants are debug and log levels,version numbers, configuration flags, and formulae.

 

Constants are defined using PHP’s define() function,which accepts two arguments: the name of the constant, and its value.Constant names must follow the same rules as variable names, with one exception: the $ prefix is not required for constant names.

 

<?php
// define constants
define ('PROGRAM', 'SkulApp');
define ('VERSION', 11.7);
// use constants
// output: 'Welcome to SkulApp (version 11.7)'
echo 'Welcome to ' . PROGRAM . ' (version ' . VERSION. ')';
?>

 

NOTE

 

By convention, constant names are usually entirelyuppercased; this is to enable their easy identification and differentiationfrom “regular” variables in a script.

 

Understanding Variable Scope

 

A key concept related to user-defined functions in PHPis variable scope: the extent of a variable’s visibility within the space of aPHP program. By default, variables used within a function are local—theirimpact is restricted to the function space alone, and they cannot be viewed ormanipulated from outside the function in which they exist.

 

Example

 

<?php
// function definition
// change the value of $score
function changeScore() {
    $score = 25;
}
// define a variable in the main program
// print its value
$score = 11;
echo 'Score is: ' . $score; // output: 11
// run the changeScore() function
changeScore();
// print $score again
echo 'Score is: ' . $score; // output: 11
?>

 

Here, the variable $score is defined in the main program, and the changeScore() function contains code to change the value of this variable. However, after running this function, the value of $score remains at its original setting, because the changes made to $score within the changeScore() function remain “local” to the function and do not reflect in the main program.

 

This “bounding” of variables to within a function space is deliberate: it maintains a degree of separation between the mainprogram and its functions, and it reduces the chances of variables from themain program affecting variables within a function.

 

However, there are certainly occasions when it may benecessary to “import” a variable from the main program into a function, or viceversa. For these situations, PHP offers the global keyword: when applied to avariable inside a function, this keyword turns the variable into a global variable,making it visible both inside and outside the function.

 

The next example illustrates the difference betweenglobal and local scope more clearly:

 

<?php
// function definition
// change the value of $score
function changeScore() {
global $score;
$score = 25;
}
// define a variable in the main program
// print its value
$score = 11;
echo 'Score is: ' . $score; // output: 11
// run the changeScore() function
changeScore();
// print $score again
echo 'Score is: ' . $score; // output: 25
?>

 

In this revision of the previous listing, the global keyword used with the $score variable within the changeScore() function changesthe scope of the variable, increasing its scope to encompass the entireprogram. As a result, changes made to the variable within the function willreflect in the main program (and vice versa). The output of the script illustrates this fact clearly.

 

You can create a file example_2.php in week_3 folder and copy and paste the above PHP script.

 

First don’t include the global in the changeScore(){ } function and run the script.

Now include the global in the changeScore(){} function and run the script. Explain why the results are different.

 

 

Functions

 

As your PHP programs get more complex, you might findyourself repeatedly writing code to perform the same task—for example, testing anumber for prime-ness or checking a form field to see if it’s empty or not. Inthese situations, it usually makes sense to turn this code into a reusable component,which can be managed independently and “called upon” as needed from different PHPprograms. Not only does this reduce the amount of duplicate code you have to write, but italso makes your scripts cleaner, more efficient, and easier to maintain.

 

Functions are reusable code segments that performspecific tasks.

 

There are functions already written in the PHPenvironment and a function written by a programmer (user-defined functions)that perform specific functions.

 

User-defined Functions

 

These are functions written by the programmer.

 

Creating and Invoking Functions

 

There are three components to every function:

 

● Arguments, which serve as inputs tothe function

● Return values, which are the outputs returned by the function

● The function body, which contains the processing code to turn inputs into outputs

 

Syntax:

 

function functionName(Argument(s) or No Argument){
     //function code comes here
           
    return $value; //Incase the function returns a value
}

 

INVOKING A FUNCTION

 

To invoke or call a function, you just need to writethe function name and pass the input value to the function incase the functionhas an argument, if no argument, just the function name and empty argument ()invokes the function

 

Examples:

 

Write a function that takes in a number and check if the number is even or not.

 

Sample Code

 

<?php
function evenNumberChecker($number){
       if($number%2==0){
             echo “<p>”.$number.” is an even number”;
       }else{
            echo “<p>”.$number.” is an old number”;
       }
}
 
//Invoke the function
$number = 4;
evenNumberChecker($number);
?>

 

Create a PHP file and name it example_3.php in theweek_3 folder and run the script.

 

In case we wish to modify the above code so that the function returns true if the number is even and returns false if not. The sample code accomplishes that.

 

<?php
function is_even($number){
     if($number%2==0){
          return true; //Returns true if number is even
     }else{
          return false; //Returns false if number is not even
     }
}
//Invoking the function
$number = 5;
if(is_even($number)){
    //function returned true, meaning number is even
    echo"<p>".$number." is even</p>";
}else{
    echo "<p>".$number."is an odd number</p>";
}
?>

 

More Examples

 

1.     Write a function that print out WELCOMETO ADVANCE WEB PROGRAMMING

2.     Write a function that takes two numbers and return the sum of the two numbers

3.     Write a function that takes two numbers and return the product of the two numbers

 

SAMPLE CODES

 

<?php
function welcome(){
    echo "<p><b>WELCOME TO ADVANCE WEBPROGRAMMING</b></p>";
}
function sum($a,$b){
    return $a+$b;
}
function product($a,$b){
    return $a*$b;
}
/* invoking the functions */
welcome();
$a = 5;
$b = 10;
echo "<p>".$a." + ".$b." = ".sum($a,$b)."</p>";
echo "<p>".$a." x ".$b." = ".product($a,$b)."</p>";
?>

 

Function names should be handled the same way as normal variable names. They should

be all lowercase, and multiword names should be separated by underscores.

 

Quality Names

 

Code in any language should be understandable by others. A function’s, class’s, or variable’s name should always reflect what that symbol is intended to do. Naming a function foo() or bar() does nothing to enhance the readability of your code; furthermore, it looks unprofessional and makes your code difficult to maintain.

 

A Class

 

PHP also allows you to group related functions together using a class.

 

Think of a class as a miniature ecosystem: it’s a self-contained, independent collection of variables and functions, which work together to perform one or more specific (and usually related) tasks. Variables within a class are called properties; functions are called methods.

 

Classes serve as templates for objects, which are specific instances of a class. Every object has properties and methods corresponding to those of its parent class. Every object instance is completely independent, with its own properties and methods, and can thus be manipulated independently of other objects of the same class.

 

Creating a class

 

Syntax:

 

class className{
     //Variablescome here
     //Examples
     public $a,$b;
     //Methods come here
    //Examples
    function sum($a,$b){
      return $a+$b;
   }
   functionproduct($a,$b){
      return $a*$b;
   }
 
}

 

More will be considered next week in the Object Oriented Programming discussion

SponsoredAdvertise