Showing posts with label Basic. Show all posts
Showing posts with label Basic. Show all posts

Using the static Statement to Remember the Value of a Variable Between Function Calls


If you declare a variable within a function in conjunction with the static statement, the variable remains local to the function, and the function "remembers" the value of the variable from execution to execution




Saving State Between Function Calls with the static Statement

Local variables within functions have a short but happy life they come into being when the function is called and die when execution is finished, as they should. Occasionally, however, you may want to give a function a rudimentary memory.
Let's assume that we want a function to keep track of the number of times it has been called so that numbered headings can be created by a script. We could, of course, use the global statement to do this, as shown in Listing below:

Accessing Variables with the global Statement

From within one function, you cannot (by default) access a variable defined in another function or elsewhere in the script. Within a function, if you attempt to use a variable with the same name, you will only set or access a local variable. Let's put this to the test :
<?php
$life = 42;
function meaningOfLife() {
echo "The meaning of life is ".$life;
}
meaningOfLife();
?>
Put these lines into a text file called scopetest2.php and place this file in your web server document root. When you access this script through your web browser, it should look like:



Variable Scope

A variable declared within a function remains local to that function. In other words, it will not be available outside the function or within other functions. In larger projects, this can save you from accidentally overwriting the contents of a variable when you declare two variables with the same name in separate functions.

Create a variable within a function and then attempts to print it outside the function:
<?php
 function test() {
      $testvariable = "this is a test variable";
 }
 echo "test variable: ".$testvariable."<br/>";
 ?>
Put these lines into a text file called scopetest.php and place this file in your web server document root. When you access this script through your web browser, it should look like 




By the Way
The exact output you see depends on your PHP error settings. That is, it may or may not produce a "notice" as shown, but it will show the lack of an additional string after "test variable".
The value of the variable $testvariable is not printed because no such variable exists outside the test() function. Remember that the attempt in line 5 to access a nonexistent variable produces a notice such as the one displayed only if your PHP settings are set to display all errors, notices, and warnings; if your error settings are not strictly set, only the string "test variable" will be shown.
Similarly, a variable declared outside a function will not automatically be available within it.

Returning User-Defined Function

A function can return a value using the return statement in conjunction with a value. The return statement stops the execution of the function and sends the value back to the calling code.

Example: creates a function that returns the sum of two numbers.

<?php
function multiply($firstnum, $secondnum) {
$result = $firstnum * $secondnum;
return $result;
}
echo multiply(9,5);
//will print "45"
?>

Put these lines into a text file called multiply.php and place this file in your web server document root. When you access this script through your web browser, it produces the following:
45

Notice in line 2 that multiply() should be called with two numeric arguments (line 6 shows those to be 9 and 5 in this case). These values are stored in the variables $firstnum and $secondnum. Predictably, multiply() multiplies the numbers contained in these variables and stores the result in a variable called $result.

The return statement can return a value or nothing at all. How we arrive at a value passed by return can vary. The value can be hard-coded:
return 4;

It can be the result of an expression:
return $a/$b;

It can be the value returned by yet another function call:
return another_function($an_argument);

function

PHP has many built-in functions. For example, strtoupper(), this function is to convert string to uppercase, another example is abs(), which is to return a value to be absolute. 
But we can also define our own function using statement:

function name_of_function($argument1, $argument2) 
{
 //function code here
}

The name of the function follows the function statement and precedes a set of parentheses. If your function requires arguments, you must place comma-separated variable names within the parentheses. These variables will be filled by the values passed to your function. Even if your function doesn't require arguments, you must nevertheless supply the parentheses.
By the way, The naming rules for functions are similar to the naming rules for variables, "The Building Blocks of PHP." Names cannot include spaces, and they must begin with a letter or an underscore. As with variables, your function names should be meaningful as well as consistent in style. The capitalization of function names is one such stylistic touch you can add to your code; using mixed case in names, such as myFunction() or handleSomeDifficultTask(), makes your code much easier to read.
see the example below:

<?php
function bold($word){
print("<b>$word</b>");
}

function italic($word) {
print("<i>$word</i>");
}

function underline($word) {
print("<u>$word</u>");
}

bold("Good Morning...");echo("<br/>");
italic("Good Afternoon...");echo("<br/>");
underline("Good Evening...");echo("<br/>");
?>
save it as function.php and open from your browser, the result should be like;

Good Morning...
Good Afternoon...
Good Evening...

all the  functions above expect a string as a paramater, so we place the variable name $word between the parentheses when we declare the function. Whatever is passed to all functions will be stored in this $word variable. Within the body of the functions,we print the $word variable, appending a <b>...</b> element to "bold function", <i>...</i> to "italic function" and <u>...</u> to "underline function".

The continue statement

The continue statement ends the execution of th current iteration but doesn't end the loop as a whole. Instead, the next iteration begins immediately. Using the previous example as in the break statement, replacing the break statement with the continue statement, we can get rid of a divide-by-zero error without ending the loop completely. See the example below:

<?php
$i = -4;
for ($i ; $i <= 10; $i++ ) {
if ( $i == 0 )
continue;
$temp = 1000/$i;
print "1000 divided by $i is... $temp<br>";
}
?>

save it as continue.php and open it through your browser. The result should be:

1000 divided by -4 is... -250
1000 divided by -3 is... -333.33333333333
1000 divided by -2 is... -500
1000 divided by -1 is... -1000
1000 divided by 1 is... 1000
1000 divided by 2 is... 500
1000 divided by 3 is... 333.33333333333
1000 divided by 4 is... 250
1000 divided by 5 is... 200
1000 divided by 6 is... 166.66666666667
1000 divided by 7 is... 142.85714285714
1000 divided by 8 is... 125
1000 divided by 9 is... 111.11111111111
1000 divided by 10 is... 100

As the result says, we know that the iteration stop temporarily if $i equals to zero and then continue the loop until finish

break statement

The break statement, though, enables you to break out of a code block.
Usually we use this in switch..case block. But we can use in loops as well as in the example below:

<?php
$i = -4;
for ($i ; $i <= 10; $i++ ) {
if ( $i == 0 )
break;
$temp = 1000/$i;
print "1000 divided by $i is... $temp<br>";
}
?>

save it as break.php and open from your browser.
We use break statement if we want to get out of a code block for probably to get rid of logic error such as division by zero or anything else.

The result should be like this:

1000 divided by -4 is... -250
1000 divided by -3 is... -333.33333333333
1000 divided by -2 is... -500
1000 divided by -1 is... -1000

The loop stop when $i equals to 0 (zero) and the loop gets out of the loop block.

do...while statement

do...while statement is a little like while statement turned on its head. The essential difference between the two is that the code block is executed before condition test and not after it.

do {
// code to be executed
//increment or decrement
} while (expression of condition) ; // only if condition is true, the code block is repeated

Remember that do...while statement always ends with a semicolon.

This type of statement will be useful when we want the code block to be executed at least once, even if in while statement evaluates to false. The code block below is executed a minimum of one time:

<?php
$i = 1;
do {
echo "The number is: $i<br />";
$i++;
} while (($i > 10) && ($i < 20));
?>

The do...while statement tests whether the variable $i contains a value that is greater than 10 and less than 20. In line 2, we initialized $1 to 1, so this expression returns false. Nonetheless, the code block is executed at least one time before the condition is evaluated, so the statement will print a single line to the browser.

The number is: 1

If we change the value of $i in line 2 to something like 10 and then run the script, the loop will display
The number is: 10
The number is: 11
The number is: 12
The number is: 13
The number is: 14
The number is: 15
The number is: 16
The number is: 17
The number is: 18
The number is: 19

"while" statement

The while statement look like this:

while (condition/s) {
// do something
//increment or decrement to limit iteration
}

the real example is below:

<?php
$counter = 1;
while ($counter <= 10) {
echo "$counter * 10 = ".($counter * 10)."<br/>";
$counter++;
}
?>


save it as while.php and open your browser. The result should be:
1 * 10 = 10
2 * 10 = 20
3 * 10 = 30
4 * 10 = 40
5 * 10 = 50
6 * 10 = 60
7 * 10 = 70
8 * 10 = 80
9 * 10 = 90
10 * 10 = 100

it's the same result as if we use "for" statement.

In this example, we initialize the variable $i, with a value of 1. The while statement tests the $i variable, so that as long as the condition(s) is true, in this case the value of $i is less than or equal to 10, the loop will continue to run. Within the while statement's code block, the value of $i is multiplied by 10 and the result is printed to the browser. In line 5, the value of $i is incremented by 1. This step is extremely important, for if you did not increment the value of the $i variable, the while expression would never resolve to false and the loop would never end.

Looping for - Meeting 10

Basically "PHP" has 3 kinds of loop, namely, "for" statement, "while" statement, and "do ... while" statement. Below we learn on "for" statement.

The regular expression of "for" statement is like this:
for (initialization; condition(s) or bound(s); increment or decrement) {
// code to be executed
}

The expressions within the parentheses of the "for" statement are separated by semicolons. Usually, the first expression initializes an $i (as a counter) variable, the second expression is the test condition for the loop, and the third expression increments or decrements the counter depending on the condition given. Below we go directly to the example:

<?php
for ($i=1; $i<=10; $i++) {
echo "$i * 10 = ".($i * 10)."<br />";
}
?>

save it as loopfor1.php and open via your browser. The result should be like this:

1 * 10 = 10
2 * 10 = 20
3 * 10 = 30
4 * 10 = 40
5 * 10 = 50
6 * 10 = 60
7 * 10 = 70
8 * 10 = 80
9 * 10 = 90
10 * 10 = 100

One thing to watch in "for" statement is that "don't forget to write the condition(s) expression" to stop looping so that the program will not loop infinitely.

"Switch" Statement - Meeting 9

"switch" statement is the alternative way to the multiple "if..elseif" conditions and can be shorter way to code than "if..elseif". The regular scripts applying "switch" staement is like this:

switch (expression) {
case result1:
// execute this if expression results in result1
break;
case result2:
// execute this if expression results in result2
break;
default:
// execute this if no break statement has been encountered hitherto
}

a switch statement will inspect expression by expression in a list of expression, and fire only one statement which is a match.

It is important to include a break statement at the end of any code that will be executed as part of a case statement. Without a break statement, the program flow will continue to the next case statement and ultimately to the default statement. In most cases, this will result in unexpected behavior, likely incorrect!

try a script below and save it as eight.php

<?php
$greeting = "morning"; //you may change to "afternoon" or "evening"
switch ($greeting) {
case "morning":
echo "Good morning";
break;
case "afternoon":
echo "Good afternoon";
break;
case "evening":
echo "Good evening";
break;
default:
echo "I don't know what to say but good $mood anyway.";
break;
}
?>

we initialize a variable $greeting with a value "morning". "switch" will evaluate each "case" and if find a match, it will be executed. In this case the result is "Good morning". Yet if we change the value of the variable $greeting to "afternoon" or "evening" the result will change accordingly.

If ... elseif - Meeting 8

We still learn more on "if" condition. In this lesson we learn on multiple conditions "if ... elseif" . We have more than two choices but still only one is fired. The script will inspect, find and execute only the "true" condition.
We still use six.php (in meeting 6 as the first file to call) to be opened from your browser, and save this script below as seven.php (rename first the previous seven.php to another filename):

<html>
<head>
<title>Conditions - cont</title>
</head>
<body>
<h3>Thank you for entering your data</h3><br>
<h4>The mark's result is:</h4>

<?php
$usrname = $_POST['usrname'];
$mark = $_POST['mark'];
if (($mark<=100)&& ($mark>90)){
print("<h3>
$usrname got <font color=#000000><b>\"A\"</b></font>
</h3>");
}
elseif (($mark<=90)&& ($mark>75)){
print("<h3>
$usrname got <font color=#0000ff><b>\"B\"</b></font>
</h3>");
}
elseif (($mark<=75)&& ($mark>60)){
print("<h3>
$usrname got <font color=#bb0000><b>\"C\"</b></font>
</h3>");
}
elseif (($mark<=60)&& ($mark>40)){
print("<h3>
$usrname got <font color=#ff0000><b>\"D\"</b></font>
</h3>");
}
elseif (($mark<=40)&& ($mark>=0)){
print("<h3>
$usrname was <font color=#ff0000>
<b><u>\"Failed\"</u></b></font>
</h3>");
}
else {
print("<h3>
<font color=##ff0000><b>\"Invalid Data\"</b></font>
</h3>");
}
?>
</body>
</html>

in the file above we also apply a little bit more complicated conditions with the hope that we can make a good progress on conditions. Try to call six.php from your browser and try some various inputs to submit and see the results.

If Else - Meeting 7

As a further lesson of "if" condition, now we learn on "if ... else " contion. In this lesson there are two choices and only one is fired. If the condition is "true" then the first statement is fired and if "false" the second statement is fired.
This is similar to the previous lesson but different. Pay attention and see the difference from the previous.

<html>
<head>
<title>Conditions - cont</title>
</head>
<body>
<h3>Thank you for entering your data</h3><br>
<h4>The mark's result is:</h4>
<?php
$usrname = $_POST['usrname'];
$mark = $_POST['mark'];
if ($mark >= 60){
print("<h3> $usrname is <font color=blue><b>\"Passed\"</b></font>
</h3>");
}
else {
print("<h3>
$usrname is <font color=red><b>\"Not Passed\"</b></font>
</h3>");
}
?>
</body>
</html>

save it as seven.php (this might overwrite the previous file unless you renamed it before save this file) and we still use six.php (in the previous lesson) file to call the form so that we can save time bu not recoding the first/origin file.

The login is, if condition is "true" then the statement in the first { } bracket is executed, if "false" the statement in the second { } bracket is executed.

If Condition - Meeting 6

Now we learn on "IF Ststement/Condition". In this example we still apply 2 files (pages) so that we can remember the previous lesson. Please pay attention to the single "if condition" below:

<html>

<head>
<title>Conditions</title>
</head>
<body>
<h3>IF Condition</h3>
<br>
Fill in a name and a exam's mark[0-100] below:
<form action="seven.php" method="post">
<pre>
Nama : <input type="text" name="usrname" size="30" maxlength="30"><br><br>
Nilai : <input type="text" name="mark" size="3" maxlength="3"><br><br>
<input type="submit" value="Send Soon!">
</pre>
</form>
</body>
</html>

save the above file as six.php
Then create a script as a new file and save it as seven.php like below:

<html>
<head>
<title>Seven</title>
</head>
<body>
<h3>Thank you for entering your data</h3><br>
<h4>The mark's result is:</h4>
<br>
<?php
$usrname = $_POST['usrname'];
$mark = $_POST['mark'];
$result = "Not Passed";
if ($mark >= 60){
$result = "Passed";
}
print("<h3>
$usrname is <font color=red><b>$result</b></font>
</h3>");

?>
</body>
</html>

Then open your browser and point to the six.php and see the result. It should show that the mark greater than or equal to 60 is "passed", if not it s "not passed".
The logic is, if the condition is "true" then the statement inside the { } bracket is executed if "false" it is not executed.

Catching Parameters - Meeting 5

In this lesson, we are learning on catching parameters from another page. So we will have 2 files as examples, the first is containing a form in which will be submitted to another page. The second is the file which will catch the first page/file.

Here is the first script:

<html><head><title>Fourth</title></head>
<body>
<center><h3>Registration</h3></center>
<hr>
Please fill your username and password in this registration form below
<form action="five.php" method="post">
<pre>
Nama : <input type="text" name="usrname" size="30" maxlength="30"><br><br>
Password : <input type="password" name="passwd" size="8" maxlength="8"><br><br>
<input type="submit" value="Send Soon!">
</pre>
</form>
</body></html>

In the script above we only apply html codes as we ignore some security aspects for this basic lesson. The most important thing is the parameter action="name.php" method="post" inside form tag, name="usrname" and name="passwd" because those parameters will be catchedby the next file/page.
Save the file as four.php


Next, here is the second script:

<html><head><title>Fifth</title></head>
<body>
<center><h3>Form Destination</h3></center>
<hr>
<h4>Thank you for submitting your registration form</h4>
We have completely received your registration form
<?php
$username = $_POST['usrname'];
$passwd = $_POST['passwd'];
print("Your username is <b>$usrname</b><br>");
print("Your password is <i>$passwd</i><br>");
?>
</body></html>


The file above must be saved as five.php. Why? It s because a page/file where the first file was addressed (see action="five.php" in the previous script). Then we catch the other two parameters with a command $_POST['...']. We are using "POST" because in the first file we used POST method. Basically we may use POST or GET method.

Data type conversion - Meeting 4

Now, we are going to learn on data type's conversion in PHP. Though in PHP we may undeclare the data-type, but we sometimes need to convert the data-type to get the exact results and avoid misleading results. Below is a script which show 3 kinds of how to convert a data-type in PHP. Please read carefully and uncomment one by one of each method of conversions to understand the functions.

<h3>Data type conversion</h3>
<hr><h4>Calculating A Circle</h4>
<?php
$rad = "10.5 cm";
define("phi",3.14);
//php has 3 ways on converting data types. to try it one by one you can uncomment each command below
/*settype($rad,"integer");*/ /*$rad = intval($rad);*/ /*$rad=(integer)$rad;*/
/*settype($rad,"double");*/ /*$rad = doubleval($rad);*/ /*$rad=(double)$rad;*/
/*settype($rad,"string);*/ /*$rad = strval($rad);*/ /*$rad=(string)$rad;*/
printf("Circle radius : %s <br>",$rad);
printf("Circle's area : %s cm<sup>2</sup><br>",($rad*$rad*phi));
printf("Circle's circumference : %s cm<br>", (2*phi*$rad));
?>

The result should be like this:


as usual, any questions can be posted via comments and so do the answers. If needed iI will create a new label providing "questions and answers". See you next meeting.

Variable and Constant - Meeting 3

Now, we are learning on variables and constants in PHP. TPlease pay attention to the scripts below:

<h3>Variables & Constant</h3>
<hr><h4>Employee's Data</h4>
<?php
$id = 19200; $name = "Mr. Bean"; $address = "Jl. Godean Gg. II/4";
define("city", "Yogyakarta");
print("ID : $ID<br>");
print("Employee's Name : $name<br>");
print("Address : $address<br>");
printf("City : %s<br>",city);
?>
<br><br><hr>
<h4>Calculating A Circle</h4>
<?php
$rad = 10; define("phi",3.14);
printf("Circle radiant : %s cm<br>",$rad);
printf("Area of a aircle : %s cm<sup>2</sup><br>",($rad*$rad*phi));
printf("Circumference of a circle : %s cm<br>", (2*phi*$rad));
?>

As before, save it as two.php and then open the file via browser. And the result should be like this:


For variables we know from the previous lesson that it must be started with $. But for constant we need to use a function "define" with 2 parameters as you can see above. The first parameter is the name of the constant and the second is the value of the constant.

Please pay attention to each line of commands and refer to the result so that you can analyse what a function is for.

As usual, any questions can be addressed via comments and so do the answers. See you in the next lessons.

First Script - Meeting 2

Before we start coding PHP, it s better to know the software environment needed to work with our scripts.
They are:
PHP, to interpret our PHP scripts.
Web server, to serve request and respond from and to users. There are many webs ervers which can serve with php scripts and one of the most popular is apache.
MySql, this is a database which is commonly paired to PHP and mostly used by php developers.

Those 3 is commonly distributed as one bundle (3 in 1). We can find it in the internet or from google with key words xampp, appserv, etc. By installing one of those bundles we will have php, apache, and mysql with a simple little setup.
One more, what we need to code is an editor. Basically we can write on any editor like notepad, wordpad, etc. Of course there are many editors which is spesifically for php and we can easily find it in the internet or by googling.
So we will not discuss about it anymore because I am going to focus in php scripts tutorial.
Well, it s time to code php now and pay attention to the script below:

<?php
print("Hello World!");
printf("<br>Today is %s ", Date("d F Y"));
$nama = "Every body"; //creating a variable must be started with $
print("<br><br>Good morning $nama, have a nice day!");
/*
this is for multilines comments
*/
printf("<hr><br>Good afternoon %s, see you tomorrow morning",$nama);
?>


save it as one.php in folder for example: C:\AppServ\www\phpisus\basic\one.php
Because i used bundle from Appserv, all files should be saved under folder \www\ if you are using another bundle probably it is under folder htdocs. Please read for each bundle carefully.
Going back to the scripts. After saving it, open your browser and point to http://localhost/phpisus/basic/one.php yous should see:


Well, it is the first script. The most principal thing of PHP code is that any PHP code must be between <?php and ?> bracket and each line of PHP commands must be ended with a semicolon (;).

For the PHP commands used above please refer to the result to analyze the command's functions in PHP.

Any question can be posted as comments and so do the answers. See you in the next meeting.

Introduction 2 Web Programming Languages - Meeting 1


Basically, there are two types of web programming languages, that is, client side languages and server side languages. Those which belong to client side languages are HTML, JavaScript, VBScript, Java Applet, and some others. And the server side ones are PHP, JSP, ASP, Servlet, .Net and some others.

The basic difference between the two is where the scripts are executed. Client side languages are executed in client side meaning in the users’s browser while server side ones are executed in servers.

Another insignificant difference is that we can simply see the client side scripts by right-clicking mouse while the server side ones can’t.

Well, from now on we will learn one of those server side languages, PHP. The question is why we choose server side langages and why PHP?

Some reasons why I prefer to choose server side language is that they are more secure as users can’t see the codes, they can connect to database and manage the data so that we can make interactive web sites with our users, and some more.

And why PHP? It s because PHP now is known as the most popular language to develop a web site. It offers many benefits to either programmers and users. PHP is easily learned, very fast, robust, and many more, you can find why PHP becomes the most users all over the world from many forums, blogs and web sites. So, no more talks about PHP and we can go on coding for the next lesson…