Simple Arrays - Arrays: PHP 7 Complete Guide: Simple, Multi-dimensional, Associative, and Object Arrays (2016)

Arrays: PHP 7 Complete Guide: Simple, Multi-dimensional, Associative, and Object Arrays (2016)

Chapter 1. Simple Arrays

After completing this chapter, the student will be able to…

Define and describe the advantages in using arrays

Create an html form that validates information contain an html array

Create a simple PHP array

Save values into a simple PHP array

Display values in a simple array

Add values from an html form into a simple array

Validate values before placing them into an array

What are arrays? Why do we need to use them?

Whenever a program uses information, that information must be stored in the memory of the computer. Individual information can be stored by creating a property.

$propertyname = value;

Property names are declared using the $ and a descriptive name for the property. PHP property names begin with a lowercase letter. If the programmer wants to use more than one word for the name, the camel case format and/or separation of the words via a special character (usually the _) can be used.

$firstName = “”;

$first_Name = “”;

$first_name = “”;

Property names should be meaningful to make your program more readable.

$a = “”;

$last_name = “”;

In the example above, $a is not meaningful. We do not have any indication of what might be stored. However, $last_name is meaningful, we understand that a person’s last name will be stored. PHP itself will not stop you from declaring a property with a capital letter. However, that is usually reserved for class names and constants.

Let’s take a quick look at a coding example that stores information using a property (or variable). Our example program will request personal information (such as name, address, city, state, zip) from a user via a web form.

Image 1-1 – example1.html

Example 1-1 – example1.html

<!DOCTYPE html>

<html lan='en'>

<head>

<title>Customer Information Form</title>

</head>

<body>

<form method='post' action='process_customer.php'>

<h2>Please enter information in all fields</h2>

First Name <input type='text' pattern='[a-zA-Z ]*' title='15 or less alphabetic characters' maxlength='15' name='first_name' id='first_name' /><br />

Last Name <input type='text' pattern='[a-zA-Z ]*' title='20 or less alphabetic characters' maxlength='20' name='last_name' id='last_name' /><br />

Address <input type='text' title='30 or less characters' maxlength='30' name='address' id='address' /><br />

City <input type='text' pattern='[a-zA-Z ]*' title='20 or less characters' maxlength='20' name='city' id='city' /><br />

State <input type='text' pattern='[a-zA-Z ]*' title='2 characters' maxlength='2' name='state' id='state' /><br />

Zip code <input type='number' min='11111' max='99999' title='5 numerical characters' name='zip_code' id='zip_code' /><br />

<input type='submit' value="Click to submit your information" />

</form>

</body>

</html>

Note: Some indenting and whitespace has been removed from the examples in this book for better viewing in your Kindle device. Download the code from the author’s website to assist you in understanding the code.

Example 1-1 provides a pretty typical web form that requests information from the user. The html shown also filters the information accepted by the user, using html 5, to insure that information was provided in the proper format.

Note: If you don’t know html, you should review some of the free tutorials and videos provided on the web. PHP is a web application language which commonly interfaces with html and JavaScript.

Once the user enters the information in the proper format and hits the submit button, the information will be sent to a program on the web server for processing. In this example, the html form line indicates that the process_customer.php application will accept and handle the information.

When the information is sent, it is actually sent as a series of properties and values (also called keys and values). The property names are determined from the values shown in the name attributes of the html form (such as first_name in the example above). Thevalues assigned to the properties are retrieved from the information entered by the user in the textboxes.

Example 1-2 – properties and values sent to process_customer.php

first_name = “Fred”

last_name = “Smith”

address = “123 Main Street”

city = “Atlanta”

state = “GA”

zip_code = “30001”

The properties created by html are very similar to properties used in PHP. This allows them to be easily processed within a PHP program. Both PHP and html create properties when they are first used. PHP considers the data type of any information that is displayed or received from an html web site to be string. Thus, as shown in Example 1-2, even though the html form requires the user to enter a number for the zip code, the value is actually stored as a string (indicated by the quotes).

PHP dynamically determines a property’s data type when a value is stored into the property. This can have advantages and disadvantages. One advantage is the ability for PHP to change the data type of information stored in a property at any time.

$zip_code = “30001”;

$zip_code = 30001;

The first statement above would place the string “30001” into the property $zip_code. If the property did not exist before, it would also be created. The second statement would change the type of information stored in $zip_code from a string to an integer.

Example 1-3 – process_customer.php

<?php

// accepts information from example1.html

// This is NOT a complete program. The validate methods shown need to be created to clean any // input.

$first_name = validate_first_name($_POST['first_name']);

$last_name = validate_last_name($_POST['last_name']);

$address = validate_address($_POST['address']);

$city = validate_city($_POST['city']);

$state = validate_state($_POST['state']);

$zip_code = validate_zip_code($_POST['zip_code']);

print "Your name is $first_name $last_name. You live at $address, $city, $state, $zip_code";

?>

A PHP program can access information passed from an html form using the $_POST or $_GET methods. The method used in the PHP program must match the type indicated in the html form attribute. Information passed via post will not display in the URLaddress in the browser. Information passed via get will display on the URL line.

Why do we have a choice?

Information passed via get does not use as much server memory because it is contain in the URL address. Information passed via post resides in the memory of the server. Sites that have heavy traffic, such as search engines, use get to be as memory efficient as possible. Although passing information via post ‘hides’ the information from the URL line, it is not consider to be secure because it is not usually encrypted.

The $_POST and $_GET methods use the property name created by the html form (‘first_name’) to retrieve the value passed (‘Fred’). The information can then be placed into a property ($first_name) that is defined in the program itself. Remember, all the information gathered via the $_POST (or $_GET) method is stored as the string data type (since the html form can only pass strings).

Since PHP dynamically creates a property the first time it is used, space is allocated in memory for the property and its value by the operating system of the web server.

$first_name = validate_first_name($_POST['first_name']);

The line above will pull the data from the first_name html textbox which resides in the form. It will validate the data, and if the data is valid, it will create the property $first_name and place the information into the property (in memory). The same process occurs for the other lines in the example above, except for the print statement. The print statement will display each of the values currently in the properties.

Note: It is very important to validate any information received from a client machine before placing it into properties in a program. This example indicates that several validate methods (such as ‘validate_first_name’) exist in the program to accomplish this task.

declare(strict_types=1);

function validate_first_name(string $value) : string

{

If ((strlen($value) <= 0) || (strlen($value) > 15))

{

throw new Exception(“Invalid First Name”);

}

return $value;

}

function validate_last_name(string $value) : string

{

If ((strlen($value) <= 0) || (strlen($value) > 20))

{

throw new Exception(“Invalid Last Name”);

}

return $value;

}

function validate_address(string $value) : string

{

If ((strlen($value) <= 0) || (strlen($value) > 30))

{

throw new Exception(“Invalid Address”);

}

return $value;

}

function validate_city(string $value) : string

{

If ((strlen($value) <= 0) || (strlen($value) > 20))

{

throw new Exception(“Invalid City”);

}

return $value;

}

function validate_state(string $value) : string

{

If ((strlen($value) <= 0) || (strlen($value) > 2))

{

throw new Exception(“Invalid State”);

}

return $value;

}

function validate_zip_code(string $value) : string

{

If ((strlen($value) <= 11111) || (strlen($value) > 99999))

{

throw new Exception(“Invalid Zip Code”);

}

return $value;

}

The validation methods shown in this example validate the values for the same type of information as was shown on the html form. For example first_name is alphabetic, with 15 or less characters. If the data is not valid, a user exception can be thrown and then caught by the calling program to inform the user of any problems.

Remember that the values have already been validated in the html form. If the data is not valid when it arrives in the PHP program, then the data was corrupted. It is logical and appropriate that an exception should be raised when this occurs.

The validate_first_name function shown uses strnlen to determine if the string passed from the html form meets these requirements. If it does, the value is returned so it can be placed into the $first_name property. If the information is not valid an exception is thrown with the message “Invalid First Name”.

Once these statements execute, the customer information is stored in memory and can be accessed by the program. If this was a complete program, the information would also be stored in a location external to the program (such as a database or cloud location) before the program completes execution. Once the program execution ends, the data is no longer accessible in memory. When a program completes, the garbage collector of the operating system is notified that the memory space is no longer needed. The garbage collector then takes the responsibility to reassign the memory space for other uses.

This process becomes more complicated, however, if the program needs the ability to store information from multiple customers.

$c1_first_name = …

$c1_last_name = …

$c1_address = …

$c1_city = …

$c1_state = …

$c1_zip_code = …

$c2_first_name = …

$c2_last_name = …

$c2_address = …

$c2_city = …

$c2_state = …

$c2_zip_code = …

The programmer could choose to create properties for every customer, in a format similar to above. However, there are several problems with this approach. First, the programmer might end up having to create a lot of properties to handle a lot of customers. If in this example we expect just a 100 customers, we would need 600 properties to hold all the information! This does not seem very reasonable or very efficient. Second, in most cases the programmer (and the company) do not know exactly how many customers will exist. It is probably not possible to determine an exact number. This is where arrays come in handy.

An array is nothing more than a container of multiple properties. The array is given a name (such as $customer_records) using the same syntax as a property. This one name is then used for storing and reviewing every value in the array. Since the same name is used to access every value in the array, there needs to be a way determine where a value is being stored or retrieved. This is done by using a subscript. In most languages a subscript is a numerical value. However, as we will see later, PHP arrays also allow alphabetic subscripts.

Note: PHP actually has only one type of arrays. This type allows numerical or alphabetic subscripts. The term “Associative Arrays” is used to describe PHP arrays with alphabetic subscripts. However, all PHP arrays are stored in memory in the same format. We will discuss associative arrays a little later.

We can replace the individual properties (such as $first_name) with the array name plus a subscript ($customer_records[0]).

Example 1-4 – process_customer_record.php

<?php

// accepts information from example1.html

// This is NOT a complete program. The validate methods shown need to be created to clean any // input

$customer_record[0] = validate_first_name($_POST['first_name']);

$customer_record[1] = validate_last_name($_POST['last_name']);

$customer_record[2] = validate_address($_POST['address']);

$customer_record[3] = validate_city($_POST['city']);

$customer_record[4] = validate_state($_POST['state']);

$customer_record[5] = validate_zip_code($_POST['zip_code']);

print "Your name is $customer_record[0] $customer_record[1].

You live at $customer_record[2], $customer_record[3],

$customer_record[4], $customer_record[5]";

?>

In Example 1-4, the individual records are replaced with locations within the array $customer_record to store the values retrieved. In most programming languages, arrays subscripts must be numbered beginning with zero. Unlike many other languages, PHP allows us to dynamically create our array locations when needed (as shown in Example 1-4). This allows us store and revive values in an array in a similar way to storing and retrieving values in properties.

In PHP, we do not have to include the subscript when storing values into an array.

Example 1-5 – process_customer_record.php

<?php

// accepts information from example1.html

// This is NOT a complete program. The validate methods shown need to be created to clean any // input

$customer_record[] = validate_first_name($_POST['first_name']);

$customer_record[] = validate_last_name($_POST['last_name']);

$customer_record[] = validate_address($_POST['address']);

$customer_record[] = validate_city($_POST['city']);

$customer_record[] = validate_state($_POST['state']);

$customer_record[] = validate_zip_code($_POST['zip_code']);

print "Your name is $customer_record[0] $customer_record[1].

You live at $customer_record[2], $customer_record[3],

$customer_record[4], $customer_record[5]";

?>

We do, however, still need to understand that the array subscripts will be automatically assigned a number (beginning with 0) as each value is placed in the array. Example 1-4 and Example 1-5 actually produce the same array. Notice, in Example 1-5, to retrieve the individual values in the array, we still have to be aware of the subscript. We can use a foreach loop to pull all values without knowing the subscript (as we will see shortly). We can also use the PHP function print_r as seen below to quickly view all contents of an array.

PHP arrays have several advantages over arrays in other languages.

$customer_record[0] = validate_first_name($_POST['first_name']);

$customer_record[2] = validate_last_name($_POST['last_name']);

If a position in an array is not given an initial value in a language like Java, that position would hold a null value. A null value is not zero, and it is not empty. If the Java program attempts to perform a calculation on a value in the array that has not been given a value, the program would produce an error indicating that a null value was in that position. If a position is skipped in a PHP array, that position merely does not exist.

print_r($customer_record);

Array ( [0] => Fred [2] => Smith [3] => 123 Main Street [4] => Atlanta [5] => GA [6] => 30001 )

As you can see from the results of executing a print_r statement against a populated $customer_record array, there is no position 1 that exists in the array.

You might wonder if this will cause any problems in retrieving values from the array.

Remember that when creating dynamic arrays in PHP we might not know how many positions are in the array. You may have been taught, or seen the for loop used with arrays. The for loop is not the best choice for retrieving values in a PHP array.

The foreach loop is a much better choice. This loop will automatically only retrieve positions that exist in the array (it would skip position 1 in the example above) and automatically retrieves all positions of an array.

foreach( $customer_record as $value)

{

print $value;

}

$customer_record is the name of the array. as is a required keyword. $value represents the value that exists within the position that the method is currently accessing. $value can be assigned any name by the programmer. It is a temporary property that holds the value in the current position in the array.

If we use this loop to print the values in the previous array, the loop would start at position 0 and print the contents of the first position (Fred). The loop would then move to the next position in the array, position 2 (there is no position 1). It would print the contents of this position (Smith) and continue until all positions in the array have been printed.

Fred Smith 123 Main Street Atlanta GA 30001

The foreach loop makes retrieving values from PHP arrays easy. Using this loop will eliminate any possibility of trying to retrieve values from non-existent positions in the array and will eliminate the possibility of going beyond the end (size of) the array. The size and positions of an array could change at any time and this little foreach loop will still function properly. We will also discover that there are many PHP functions that eliminate the need to use loops when reading, retrieving, or updating values in an array.

Other Ways to Define Arrays

In PHP, if you know the initial values for an array, it can be created using a structure similar to other languages.

$customer_record = array(‘Fred’, ‘Smith’, ‘123 Main Street’, ‘Atlanta’, ‘GA’, ‘30001’);

print_r($customer_record);

Array ( [0] => Fred [1] => Smith [2] => 123 Main Street [3] => Atlanta [4] => GA [5] => 30001 )

In this example, we have initially created the array with a certain number of elements (6) and initial values. PHP, like other languages, will automatically number the subscripts for each position, beginning at zero. Since PHP stores all arrays in the same format, we can change the values in this array using the same techniques we have discussed.

$customer_record[0] = ‘Pete’;

print_r($customer_record);

Array ( [0] => Pete [1] => Smith [2] => 123 Main Street [3] => Atlanta [4] => GA [5] => 30001 )

As you can see, Fred is replaced by Pete, by passing a new value into the proper position.

What happens if we attempt to place a value in a position that does not exist?

$customer_record[6] = ‘7707777777’;

print_r($customer_record);

Array ( [0] => Pete [1] => Smith [2] => 123 Main Street [3] => Atlanta [4] => GA [5] => 30001 [6] => 7707777777 )

As you can see, the array simply creates a new position and places the value in that position.

$customer_record[] = ‘7707777777’;

PHP arrays will automatically place new values at the end of the array if a position is not included. This is not true in other languages. Many languages will indicate that you are out of bounds (you have exceeded the size of the array). They will not let you add elements to the array unless you somehow increase the size of the array.

In the format used in the example above, the original array contains the exact same information and positions as the previous array. PHP allows us to easily append a value to the end of any existing array, no matter how it was declared initially.

What happens if we load a number into a position in this array instead of a string?

$customer_record[5] = 30001;

Array ( [0] => Pete [1] => Smith [2] => 123 Main Street [3] => Atlanta [4] => GA [5] => 30001 )

The output of a print_r statement would produce similar results (because it makes no indication of the data types of the individual values).

However, we can detect the difference if we first convert our array to JSON format (using the method json_encode), and then display the results. We could also use the PHP var_dump method. We will look at examples using this method in a later chapter.

$json = json_encode($customer_record);

print_r($json);

["Pete","Smith","123 Main Street","Atlanta","GA",30001]

The JSON format allows you to see that the data type for the zip code did actually change from a string value (‘30001’) to a numeric value (30001). Even if the zip code already existed in string format, when we replace it with a numerical value, that number (not string) would now exist in the array.

Html Arrays

Now that we have a general idea of how arrays work in PHP, we can also use this concept with our html form and discover that we can easily pass an array into our PHP program.

Example 1-6 – example1_array.html

<!DOCTYPE html>

<html lan='en'>

<head>

<title>Customer Information Form</title>

</head>

<body>

<form method='post' action='process_customer_array.php'>

<h2> Please enter information in all fields</h2>

First Name <input type='text' pattern='[a-zA-Z ]*'

title='15 or less alphabetic characters' maxlength='15'

name='customer_record[0]' id='customer_record[0]' /><br />

Last Name <input type='text' pattern='[a-zA-Z ]*'

title='20 or less alphabetic characters' maxlength='20'

name='customer_record[1]' id='customer_record[1]' /><br />

Address <input type='text' title='30 or less characters'

maxlength='30' name='customer_record[2]'

id='customer_record[2]' /><br />

City <input type='text' pattern='[a-zA-Z ]*'

title='20 or less characters' maxlength='20'

name='customer_record[3]' id='customer_record[3]' /><br />

State <input type='text' pattern='[a-zA-Z ]*'

title='2 characters' maxlength='2'

name='customer_record[4]' id='customer_record[4]' /><br />

Zip code <input type='number' min='11111' max='99999'

title='5 numerical characters' name='customer_record[5]'

id='customer_record[5]' /><br />

<input type='submit'

value="Click to submit your information" />

</form>

</body>

</html>

In Example 1-5, each html name element has been replaced by a position in the customer_record array. This html array is dynamically created, just like PHP arrays. The value in the first textbox (which will be the customers first name) is now placed intocustomer_record[0].

The html form can now pass this array to the PHP program via the post method without any other changes.

Example 1-7 – process_customer_array.php

<?php

$customer = filter_input_array(INPUT_POST);

$customer_record = validate_array($customer["customer_record"]);

print "Your name is $customer_record[0] $customer_record[1].

You live at $customer_record[2], $customer_record[3],

$customer_record[4], $customer_record[5]";

?>

As you can see from Example 1-7, we actually can use less coding to pull the html array into the program. The program includes a PHP filter_input_array method which pulls in the complete array created by the html form. It also filters out any harmful data (such as html symbols <>).

Note: The filter_input_array method would not verify that the fields have the correct information, such as 15 or less alphabetic characters in the first_name field (now called customer_record[0]). A validate_array method can be created to accept the array and pass individual values to the correct validation method.

function validate_array( $input_array);

{

$value = validate_first_name($input_array[0]);

$value = validate_last_name($input_array[1]);

$value = validate_address($input_array[2]);

$value = validate_city($input_array[3]);

$value = validate_state($input_array[4]);

$value = validate_zip_code($input_array[5]);

return $input_array;

}

Assuming that each of the validate methods will throw an exception if there is a problem, this method can assume every field is validated if the flow reaches the end of the method. The method returns the array passed so the array can be placed in$customer_record. $value does hold the individual values returned. However, it exists only to allow the individual validate methods to still include a return statement as shown previously. We could, of course remove the return statement and $value = would not be needed

In Example 1-7, $customer_record = validate_array($customer["customer_record"]) searches for the array named customer_record and places that array into $customer_record in the PHP program after calling validate_array. This actually turns $customer_record into an array of the values passed from the textboxes on the form. There is no longer a need to populate individual positions in $customer_record via additional PHP code. This was all completed with one code line!

Deleting

Array (

[0] => Fred [1] => Smith [2] => 123 Main Street [3] => Atlanta [4] => GA [5] => 30001

)

A programming logic textbook would explain the necessity to create a loop to remove a value in the middle of an array like the one shown above. If we were to remove the second value ([1]), the text book would explain that each value after the one removed (‘123 Main Street’, ‘Atlanta’, ‘GA’, 30001) would need to be repositioned into the subscript above it to fill in the value that was removed. This is usually necessary to avoid any NULL values.

Array (

[0] => Fred [1] => 123 Main Street [2] => Atlanta [3] => GA [4] => 30001

)

The loop would update the array to something similar to the above example.

In PHP, this is not necessary. As explained earlier, PHP arrays work very well with missing subscripts. The foreach loop automatically skips over missing subscripts. Thus, we can remove any subscript from an array by creating a very simple function.

Example 1-8 deletesubscript.php

$customer_record = array('Pete' ,'Smith' ,'123 Main Street' ,'Atlanta','GA', 30001);

declare(strict_types=1);

function delete_array_value(int $subscript)

{

unset($customer_record[$subscript]);

}

delete_array_value(1);

Example 1-8 uses the method unset to remove whatever subscript is passed into the function delete_array_value. In this example the delete method would remove the location of Smith from the array. The array would now contain:

$customer_record = array('Pete','123 Main Street' ,'Atlanta','GA', 30001);

If we execute the following statement, you will see that the subscript and its value have been removed.

Print_r($customer_record);

Array (

[0] => Pete

[2] => 123 Main Street

[3] => Atlanta

[4] => GA

[5] => 30001

}

Updating & Inserting

Actually we have already shown several examples on updating values in arrays. Let’s look at another.

Example 1-9 insert.php

$customer_record = array('Pete' ,'Smith' ,'123 Main Street' ,'Atlanta','GA', 30001);

function insert_array_value( $value )

{

array_push($customer_record, $value);

}

insert_array_value(‘770-777-7777’);

In example 1-9, the function array_push is used to add values to the end of the array. The phone number would be placed into position 6 in the $customer_record array just after the zip code.

To create an update method, we can just make a slight change to this example.

Example 1-10 update.php

$customer_record = array('Pete' ,'Smith' ,'123 Main Street' ,'Atlanta','GA', 30001);

declare(strict_types=1);

function update_array_value( int $position, $value )

{

$customer_record[$position] = $value;

}

update_array_value(0, ‘Peter’’);

In Example 1-10, both the position (subscript) and the value are passed into the function. The array is then updated by passing the value into the location in the $customer_record array.

Let’s look at a method that combines these ideas.

Example 1-11 update_insert_value

$customer_record = array('Pete' ,'Smith' ,'123 Main Street' ,'Atlanta','GA', 30001);

declare(strict_types=1);

function update_array_value( $value, int $subscript = -1)

{

If( $subscript != -1)

{ $customer_record[$subscript] = $value; }

else

{ array_push($customer_record, $value); }

}

update_array_value(“770-777-7777”, 6);

update_array_value(“770-777-7777”);

update_array_value(“Peter”, 0);

This update method allows us to insert individual values or actually replace values. If the subscript is passed, then the value passed is placed into the location requested. If a subscript is not provided, the array_push function is called to place the value at the end of the array.

update_array_value(“770-777-7777”, 6);

Using the statement above, the phone number would be placed in position six. Even though there is not a position six in this example, PHP will create a position six, as we have seen from other examples. Thus, this call is actually inserting the phone number.

update_array_value(“770-777-7777”);

Using this format, causes the $subscript to be set to -1 since a default value was provided in the function declaration statement.

function update_array_value( $value, int $subscript = -1)

This will cause the else part of the if statement to execute.

If( $subscript != -1)

The array_push function will then be used to insert the phone number at the end of the array. This also places the phone number is position six.

update_array_value(“Peter”, 0);

This final statement passes both an exisiting subscript and a value. This would cause the top of the if statement to execute. The value (Peter) would replace the current value in position 1.

As you will see frequently, once you get use to using arrays, you will find the amount of code needed to process the information is much less. Example 1-7 has only four executable statements. Example 1-3 (and Example 1-4) had seven executable statements.This demonstrates that using arrays is more efficient than using individual properties. Arrays provide us the ability to expand (or contact) their size, and allow us to easily adjust the data types stored.

Before we look at multi-dimensional arrays, let’s take a break and do some practice exercises.

Exercises

(You can download all working examples from this chapter at: http://www.littleoceanwaves.com/understandingarrays/)

1. Create an html form to accept information about a book (such as book name, book author, publisher, ISBN number). Use html 5 to validate the input provided by the user. Pass the information into a PHP program which will then display the information back to the user.

2. How does using arrays make a program more efficient?

3. How are PHP arrays different than arrays in other programming languages?