getting started with PHP :: part 2

Functions, if statement and forms.

Picking up from where we left off…

Basic mathematical functions

Perhaps the most basic functionality that can be achieved using PHP is as a form of calculator. It’s as easy as;

<?
$a=7;
$b=10;
?>
<p>a plus b = <? echo $a+$b; ?></p>
<p>b minus a = <? echo $b-$a; ?></p>
<p>(b minus a) plus (b times a) divided by two = <? echo (($b-$a)+($b*$a)/2); ?></p>

The above example is okay, but you can also create a function that will use numbers that you pass to it on the fly such as..

function addNumbers($c,$d){
$result=$c+$d;
return $result;
}

function mentalMix($c,$d){
$result=($c+$d)*$c-$d;
return $result;
}

and then call these functions like so;

echo(addNumbers(5,5));
echo(mentalMix(25,18));

When you call the function, you’re also passing two numbers to the function which get used as the variables $c and $d within the function.

We can also combine this with a form so that the numbers that are used in the function can be inputted (is that a word?) by the user. We’ll come to that shortly..

if statements

An if statement is used to run a piece of code depending on whether a condition is met. For instance if we refer back to our $a and $b variables, we can write

if($a==$b){
echo("<p>The numbers $a and $b are the same.</p>");
}

This will only echo the string on the second line if the numbers are the same. If not, then nothing would happen.

An if - else statement provides an alternative in case our condition is not met.

$name = "matt";
if($name == "matt"){
echo("Hello matt!");
}else{
echo("Your name isn't matt! It's " . $name . "! Impostor!");
}

If you change the string value in the name variable you will see that the ‘else’ code is executed.

You’re not matt!

You can also stack up several if statements to thoroughly evaluate a condition like so;

if($a==$b){
echo("<p>The numbers $a and $b are the same.</p>");
}else if($a>$b){
echo("<p>$a is clearly larger than $b.</p>");
}else if($a<$b){
echo("<p>Everyone can see that $a is smaller than $b.</p>");
}

for - loops

A for - loop will essentially repeat a piece of code a certain number of times until a condition is met. The basic structure of for loop is something like;

for(first value; condition; increment / decrement) {
//body of loop
// increment / decrement
}

The first value is what the loop will begin with; the condition is used to decide when to stop looping; and the final part will either add or take away from the initial value. That’ll probably make more sense when you see it in action.

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

This starts off with $i being equal to 1 and continues for as long as $i is less than 10. It’ll add 1 to $i every time it completes a loop but not before echoing what the current value of $i is (with a linebreak just to place each value on a new line). If you run this one, you’ll see it that it simply counts up to 9 (because when $i is ‘10′, it’s no longer less than 10).

Similar to the for - loop is a while - loop which will just continue to execute a piece of code while a condition remains true. For instance,

$i=1;
while($i<10){
echo($i."<br />");
$i++;
}

will produce the same result as the previous for - loop. It specifies the initial value of $i and echoes that value for as long as $i is less than 10, adding 1 to $i every time. If you want to see that this really will repeat forever as long as $i is less than 10, then take out the $i++ so that $i constantly remains ‘1′. I don’t recommend it though. It made my browser very slow.

Forms

PHP can extract values from a submitted form and convert them into variables that you can use in various ways. If you now create a simple form, we’ll go about linking it to a separate script page to extract information.

(Create a new php page, save it as ‘form1.php’ and place a form on it with the name of ‘form_test’. Set the action to ‘process_form.php’ (which will be the page we send this form to) and set the method to ‘post’. Then place a text field inside this form with the name of ‘text’ and finally add a submit button.)

<form name="form_test" method="post" action="process_form.php">
Enter some text: <input type="text" name="message" id="text">
<input type="submit" name="button" id="button" value="Submit">
</form>

Form 1

Then create a new page and save it as ‘process_form.php’. On this page, add the following PHP:

$message = $_POST['message'];
echo ("<h2>Your message was $message</h2>");

This creates a variable called $message and assigns to it the value of our ‘message’ field from the form. We can then echo that variable onto the new page. Now upload both pages, browse to your form1.php page and enter some text. You should then be taken to a page which will display the text that you entered!

Form action

This currently takes information from one page and displays it on another one, but by changing the form action to

<?php echo($_SERVER['PHP_SELF']); ?>

you can make the page ‘refresh’ itself with the entered data. Don’t forget to add the message code from above to the page that has your form on!

The problem with this is that your page will echo the term ‘Your message was’ when you first browse to it, despite the fact that you’ve not submitted a message yet. So by adding an if statement, we can make sure that the echo only occurs if the form has been posted.

if (isset($_POST['message'])){
$message = $_POST['message'];
echo ("<h2>Your message was $message</h2>");
}

Calculator

Returning to the mathematical functions at the start, we can create a form which allows users to enter their own numbers to a defined function. Create a new page, save it as ‘calc.php’ and add the following PHP to the very top of the page.

$a=$_POST['first'];
$b=$_POST['second'];
$product=addNumbers($a,$b);
function addNumbers($a,$b){
$result=$a+$b;
return $result;
}

Then add the following form.

<form id="calc" name="calc" method="post" action="<?php echo($_SERVER['PHP_SELF']); ?>">
<p>
<input type="text" name="first" id="first" /><br />
<input type="text" name="second" id="second" />
</p>
<p>= <?php echo($product); ?></p>
<p><input type="submit" name="button" id="button" value="Submit" /></p>
</form>

This will produce a form that adds up any two numbers you enter. Maths are great.

To make a ‘fully working’ calculator, you could add another textfield between your two current ones and give it a name of ‘method’. Then change the PHP at the top of your page to read like:

$a=$_POST['first'];
$b=$_POST['second'];
$method=$_POST['method'];
if ($method == '+') {
$product=addNumbers($a,$b);
}
elseif ($method == '-') {
$product=subtractNumbers($a,$b);
}
elseif ($method == '*') {
$product=multiplyNumbers($a,$b);
}
elseif ($method == '/') {
$product=divideNumbers($a,$b);
}
else {
$product=mangleNumbers($a,$b);
}
function addNumbers($a,$b){
$result=$a+$b;
return $result;
}
function subtractNumbers($a,$b){
$result=$a-$b;
return $result;
}
function multiplyNumbers($a,$b){
$result=$a*$b;
return $result;
}
function divideNumbers($a,$b){
$result=$a/$b;
return $result;
}
function mangleNumbers($a,$b){
$result=(($a+$b*$a)/$a)*$b+$a;
return $result;
}

This sets up a variety of functions and selects which one to run depending on the method you submit. If it doesn’t recognise what you’ve submitted as either + - * or / then it’ll just mangle your numbers up!

Finally, you can assign each of your textfields an appropriate initial value so that when you are presented with your result, you can still see the calculation you actually submitted.

value="<? echo $a; ?>"

etc..

initial value

Stuff.