Lesson 5 - Associative arrays in PHP and submitting forms

PHP Basic constructs Associative arrays in PHP and submitting forms

In the previous lesson, Strings and arrays in PHP, you learned to use various string declarations and were introduced to arrays. In today's lesson, we're going to expand your knowledge of arrays and use it to create a web calculator. Yes, we're finally going to react to user input!

Associative arrays

The second type of arrays in PHP is called associative. An associative array works just like an indexed array. However, associative indexes are not only numeric, they're also strings. We refer to associative array indexes as keys.

We declare an associative array just like an indexed array, the main difference being that we have to define their keys as well. We use a double arrow (=>) operator to do just that:

$favoriteThings = array(
        'homer' => 'donut',
        'marge' => 'oven',
        'bart' => 'slingshot',
        'lisa' => 'book',
        'maggie' => 'doll',
);

We formatted the array declaration in multiple lines to improve readability, but we could write it on a single line as well. There are 5 values in the array: 'donut', 'oven', 'slingshot', 'book', 'doll'. Each value belongs to a key ('homer', marge', 'bart', 'lisa', 'maggie'). We use arrows to associate each value to its key and separate them with commas. I left a comma after the last value as well so that I wouldn't forget to add it later on (doing so is a good practice).

By the way, notice that when we create a variable whose name consists of two or more words, we use the camelCase notation. The first letter is lowercase and the first letter of each following word is uppercase. People use various notations to write PHP code but this one is, without a doubt, the best.

We can work with associative arrays in the same as we did previously with indexed arrays:

echo('Homer likes: ' . $favoriteThings['homer']);

Instead of writing $favoriteThings[0], we use the string key. The main advantage to using associative arrays is better readability. We actually see what we're getting off an array. Whereas with numeric indexes, we may not even know what the value is.

Every indexed array can be declared as associative using the following format:

$backpack = array('rope', 'flashlight', 'wallet');

$backpack2 = array(
        0 => 'rope',
        1 => 'flashlight',
        2 => 'wallet',
);

print_r($backpack);
print_r($backpack2);

Based on the output, we can see that the $backpack and $backpack2 arrays are completely identical. Internally, PHP only provides associative arrays. When we create an indexed array, what it does is create an associative array and generate keys for its values based off of their order.

*Note: In most programming languages, the array size is limited and once we create it, we're not able to add any more elements. However, PHP does not have limitations on what you can do with an array.

Processing forms in PHP

Now that that's all said and done, we can get to the good stuff! Applications that react to user input. We'll start out by programming a simple calculator.

Web applications can accept input through two methods - GET and POST. Although the HTTP protocol supports other methods, REST, most web browsers don't support them. The PHP script will always receive the data in an associative array which is named in the same way as the method through which the output has been derived.

Let's create a folder for our new application, I'll name mine Calculator.

The GET method

Create a calculator.php file. To pass data to this script using the GET method, we'll add them to the URL using a query string. A query string starts with a question-mark (?) and the individual parameters are separated with ampersands (&). A "=" character must also be included between each parameter name and its value.

If we type this in the URL address:

localhost/calculator/calculator.php?number1=10&number2=20

It would be the equivalent of passing two variables to the script using the GET method. The first one is named number1 with a value of 10, and the second is number2 with a value of 20.

The contents of the script could be set up as follows:

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Calculator</title>
    </head>
    <body>
        <?php
            $sum = $_GET['number1'] + $_GET['number2'];
            echo("Sum: $sum");
        ?>
    </body>
</html>

The script works with the superglobal $_GET array. It's superglobal because it's accessible from basically everywhere. There, we would find all of the variables that were sent to the script from the query string. The array is associative, we use the name of each of the variables as the key and get its value the same way. Then, we simply print the sum of the two values.

The result:

Calculator
localhost/cal­culator/calcu­lator.php?num­ber1=10&number2=20

The GET method is useful when setting up subpages, however, it doesn't suit our needs at the moment.

The POST method

The POST method is used, in most cases, when submitting forms. Our application will then consist of 2 files. The first file will contain a form into which the user will enter 2 numbers and submit it through the "Compute" button. It would then send the data to the second file which will contain a PHP script that computes the result.

calculator.html

This file contains the form. We could give it the .php extension, but doing so is not necessary since it doesn't contain PHP blocks. If you name this file index.html, it would be displayed as the default page when you access the calculator folder. The file contents will be as follows:

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Calculator</title>
    </head>
    <body>
        <p>Welcome to the calculator, please enter 2 numbers and you will get their sum.</p>

        <form method="POST" action="sum.php">
            <input name="number1" type="text" /><br />
            <input name="number2" type="text" /><br />
            <input type="submit" value="Compute" />
        </form>

    </body>
</html>

The result should look like this:

Calculator
localhost/cal­culator/calcu­lator.html

We now have a website containing a form with several input fields. If you prefer HTML 5, you can use "number" as the input type. The last field is the submit button which will submit the form.

The form attributes are the interesting part here. Method="POST" defines the method through which the form data will be submitted. Although POST is not the default value, it really doesn't make sense for us to use any other one. If we don't provide the Method attribute, the method would be implicitly set to GET where the form data would be submitted as a query string in the URL address. Anyone would be able to see the values and their size would be limited. I highly suggest using the POST method in this case. The action attribute sets the script (the file containing the script) that will process the form. If we don't provide this attribute, the form will be sent to the same file in which it is declared.

sum.php

This file is the script containing code that processes the data that is sent to it by the form. As you may have guessed, the form data will be received in the $_POST superglobal array. It's an associative array as well and its keys are the same as the form's input fields (the values of their name attribute).

The script will contain the following code:

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Calculator</title>
    </head>
    <body>
        <?php
            $sum = $_POST['number1'] + $_POST['number2'];
            echo("Sum: $sum");
        ?>
    </body>
</html>

Compared to the processing script using the GET method, the script content hasn't changed at all. Go ahead and test your calculator to make sure that it actually works :)

I look forward to seeing you all in the next lesson, Conditions in PHP, where we'll introduce you to conditions. The projects are available for download below.


 

Download

Downloaded 51x (2.17 kB)
Application includes source codes in language PHP

 

 

Article has been written for you by David Capka
Avatar
Do you like this article?
2 votes
The author is a programmer, who likes web technologies and being the lead/chief article writer at ICT.social. He shares his knowledge with the community and is always looking to improve. He believes that anyone can do what they set their mind to.
Unicorn College The author learned IT at the Unicorn College - a prestigious college providing education on IT and economics.
Thumbnail
Previous article
Strings and arrays in PHP
Thumbnail
All articles in this section
PHP basic constructs
Activities (11)

 

 

Comments

Avatar
belay ozil
Member
Avatar
belay ozil:6/12/2017 10:01

the calculator zip code is not working for me what's the problem?????????

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Calcula­tor</title>
</head>
<body>
<?php
<p>Welcome to the calculator, please enter 2 numbers and you will get their sum.</p>

<form method="POST" action="sum.php">
<input name="number1" type="text" />

<input name="number2" type="text" />

<input type="submit" value="compute" />

$sum = $_GET['number1'] + $_GET['number2'];
echo("Sum: $sum");

$sum = $_POST['number1'] + $_POST['number2'];
echo("Sum: $sum");

</form>
?>

</form>

</body>
</html>

Reply 6/12/2017 10:01
programming is my life
Avatar
David Capka
ICT.social team
Avatar
Replies to belay ozil
David Capka:6/12/2017 10:40

This is not the code from our zip archive. You're mixing PHP and HTML code. Download the zip archive and look into the files, it'll help you to understand your mistakes.

Reply 6/12/2017 10:40
You can walk through a storm and feel the wind but you know you are not the wind.
To maintain the quality of discussion, we only allow registered members to comment. Sign in. If you're new, Sign up, it's free.

2 messages from 2 displayed.