Multi-dimensional 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 2. Multi-dimensional Arrays

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

Define and describe the advantages in using multi-dimensional arrays

Compare a table with a multi-dimensional array

Create a multi-dimensional PHP array

Save values into a multi-dimensional PHP array

Display values in a multi-dimensional array

Add values from an html form into a multi-dimensional array

Validate values before placing them into a multi-dimensional array

Convert JSON data read from a text file into a PHP array

Convert PHP arrays to JSON objects and save to a text file

Save array information to a MySQL Database

The previous chapter showed us how efficient arrays can be.

However, the question that was not answered is

“How do we handle data from multiple customers?”

A simple array holds information that is related a particular individual component, such as a customer. In order to hold all customers information in memory, we must think in more than one dimension. We need to have the ability to hold multiple components of customer information. We can think of a doctor’s office (before everything became computerized) keeping records of each patient in a file, with all the files for all the patients being stored within a file cabinet.

Multi-dimensional arrays work in a similar way. A customer’s information is stored in a ‘record’ (similar to the file in the doctor’s office). In our previous example, all of the information related to Fred Smith is kept together in a ‘record’. Multiple records (just like the file cabinet) are kept together in a ‘table’. The ‘table’ would contain all of the customer records.

Spreadsheets work in the same way.

Figure 2-1 Customers Table

"Pete" "Smith" "123 Main Street"

"Atlanta" "GA" 30001

"Sally" "Parisi" "101 South Street"

"Atlanta" "GA" 30001

"Jake" "Boukari" "111 Peachtree Street"

"Atlanta" "GA" 30011

"Cap" "Hill" "1112 Peachtree Road"

"Atlanta" "GA" 30018

In Figure 2-1, four customers exist within the table. In a spreadsheet or in a program, the information for each customer is contained in a record (also referred to as a row). Each row has the same type of information in each column. For example, the firstcolumn contains the first name of each of the customers.

This table contains six columns and four rows. However, remember that spreadsheets and programs begin the numbering of elements with zero, not one. The uppermost left element (which contains “Pete”) resides in row zero and column zero (0, 0). The lowermost right element (30018) resides in row three and column 5 (3, 5).

What resides in row 2 and column 2? “111 Peachtree Street”

Why do we say row x and column y, not column y and row x?

The answer lies in how the information is stored in memory. The operating system stores two dimensional arrays by row. The rows are keep intact because everything in a row is related (all of Pete Smith’s information). The row information is placed in memory locations that are contiguous to each other (next to each other). Other rows are not necessary stored in memory next to previous rows. This allow the operating system to be efficient with memory storage.

When retrieving data from a two-dimensional array, we usually retrieve or look at a row of information at a time (such as all of Pete Smith’s information). This in turn allows the operating system to go to one continuous area of memory to pull the information. When a column of information is needed, less efficiently occurs, because the operating system might need to go to several noncontiguous locations in memory to retrieve the information.

When we store information into a table, or array, we also (usually) store a complete row of information first (all of Pete Smith’s information) before storing another row of information. This again, maps to the operating system storing all the related information into the same general location of memory before it save the next row of information (possibly at a completely different location in memory).

All this just leads us to remember to always list the row first, and then the column when saving or retrieving information in a two-dimensional array.

print $customer_record[0];

In chapter 1, we discovered that the statement above would print out the first name of the customer (‘Pete’). However, if the array is two-dimensional, this statement will pull the complete first row, instead of the first record. To read a specific record, both the row and column must be specified.

print $customer_record[1][0];

In this statement, the first subscript indicates the row (1), and the second subscript indicates the column (0). If the table shown previous is an array, this statement would print Sally.

What would print $customer_record[2][4]; display? GA

To dynamically create a two-dimensional array in PHP, we use almost the same statements that we used for a single dimension.

$customer_record[0][0] = “Pete”;

$customer_record[0][1] = “Smith”;

$customer_record[0][2] = “123 Main Street”;

$customer_record[0][3] = “Atlanta”;

$customer_record[0][4] = “GA”;

$customer_record[0][5] = 30001;

$customer_record[1][0] = “Sally”;

$customer_record[1][1] = “Parisi”;

$customer_record[1][2] = “101 South Street”;

$customer_record[1][3] = “Atlanta”;

$customer_record[1][4] = “GA”;

$customer_record[1][5] = 30001;

Let’s look at what we see when we use the print_r method on the array we just created.

print_r($customer_record);

Array (

[0] =>

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

[1] =>

Array ( [0] => Sally [1] => Parisi [2] => 101 South Street [3] => Atlanta [4] => GA [5] => 30001 )

)

Note: The print_r method will display the information above without the line breaks that have been added.

The outside array (Array ( ) ) controls the rows, which are actually their own arrays. In this example, there are two rows indicated by [0]=> and [1]=> (on the lines by themselves). Inside of each row is an Array that controls the columns for that row. The firstArray contains the information about Pete Smith. The second Array contains information about Sally Parisi. You should notice that these arrays are exactly the same format as the one dimensional array that we discussed in chapter 1. In PHP, two-dimensional arrays are actually individual one-dimensional arrays held together by an array that surrounds them.

Can we create this two dimensional array without specifying the subscript numbers (as shown with one dimensional arrays)?

When using the dynamic approach of creating the positions when needed, we have to tell PHP when to start a new array or row (when to switch from the array which contains the Pete information to the array that contains the Sally information). One way we can do this is by using a counting variable.

Example 2-1 process_customer_twodim.php

<?php

$I = -1;

$customer_record[++$I][] = 'Pete';

$customer_record[$I][] = 'Smith';

$customer_record[$I][] = '123 Main Street';

$customer_record[$I][] = 'Atlanta';

$customer_record[$I][] = 'GA';

$customer_record[$I][] = 30001;

$customer_record[++$I][] = 'Sally';

$customer_record[$I][] = 'Parisi';

$customer_record[$I][] = '101 South Street';

$customer_record[$I][] = 'Atlanta';

$customer_record[$I][] = 'GA';

$customer_record[$I][] = 30001;

print_r($customer_record);

?>

In Example 2-1, A counting variable $I is created with an initial value of -1. In the next statement, the variable is incremented before it is used (++$I). The value in the variable (0) is used to define the initial subscript for the array containing the information for Pete. The remaining values for Pete are placed into the related array using $I, which is still set to 0 each time. When it is time to create the array holding the information for Sally, the counting variable is again incremented. This provides a subscript number of 1 for each value placed in the Sally array. Notice that we did not need to provide a value for any of the positions with the Pete or Sally array.

However, this is not the most efficient way! This not good coding. Don’t create your two-dimensional arrays using this example!

What would happen if we didn’t place the counting variable or a number in the first subscript positions (such as $customer_record[][] = ‘Pete’;)?

Each value for Pete and Sally would end up with its own array and only one subscript. Each of the two subscripts would increment each time. Download Example 2-1 and remove every place that $I occurs and run the program to see the mess it would produce!

We could eliminate the need for using the counting variable if we define the complete array at one time.

$customer_record = array (

array(‘Pete’ , ‘Smith’ , ‘123 Main Street’ , ‘Atlanta’, ‘GA’, 30001),

array(‘Sally’ , ’Parisi’ , ‘101 South Street’ , ‘Atlanta’ , ‘GA’ , 30001)

);

This approach is a lot more efficient; taking a lot less lines of code to create. It produces the same results as Example 2-1. You do need to be careful to include all the required commas as shown above. Also note that the semicolon is still needed at the end of the complete statement.

We can still change and add additional values in the array using the approach we have seen before.

$customer_record[0][0] = ‘Peter’;

$customer_record[0][6] = ‘770-770-7777’;

$customer_record[2] = array(‘Jake’ , ‘Boukari’ ,

‘111 Peachtree Street’ , ‘Atlanta’ , ‘GA’ , 30011);

Array (

[0] => Array ( [0] => Pete [1] => Peter [2] => 123 Main Street [3] => Atlanta [4] => GA [5] => 30001 [6] => 770-770-7777 )

[1] => Array ( [0] => Sally [1] => Parisi [2] => 101 South Street [3] => Atlanta [4] => GA [5] => 30001 )

[2] => Array ( [0] => Jake [1] => Boukari [2] => 111 Peachtree Street [3] => Atlanta [4] => GA [5] => 30011 )

)

PHP arrays allow a lot of flexibility. We are able to change a value in the original array (replacing Pete with Peter). We are able to add another value to the array containing Peter information (the array now contains his phone number). We were also able to add a complete new array inside the customer_record array (There is now a Jake array). To accomplish some of these tasks in other programming languages would take a lot more code.

However, we are not dynamically creating the array as we have seen previously. Soon we will see an example showing us how to dynamically create an array and add rows without knowing the size of the current array.

Html Arrays

This is all pretty neat, but can we still easily add customer information coming from a web page into our two dimensional array as we did in chapter 1?

The answer is YES!

Example 2-2 – example2_array.html

<!DOCTYPE html>

<html lan='en'>

<head>

<title>Customer Information Form</title>

</head>

<body>

<form method='post' action='process_customer_array_twodim.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>

The only change made to the html file (Example 2-2) is to change the name of the PHP program called (process_customer_array_twodim.php).

Example 2-3 – process_customer_array_twodim.php

<?php

$customer_record = array (

array('Pete' , 'Smith' , '123 Main Street' , 'Atlanta', 'GA', 30001),

array('Sally' , 'Parisi' , '101 South Street' , 'Atlanta' , 'GA' , 30001)

);

$customer = filter_input_array(INPUT_POST);

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

array_push($customer_record, $customer_info);

print_r($customer_record);

?>

In Example 2-3, a two-dimensional array ($customer_record) is declared. The process to add the html data to the array requires only one additional line to be added to the example from chapter 1. The PHP method array_push determines the size of an existing array and adds values to the end of an existing array. $customer_info contains the array of values the customer entered into the html form. array_push attachs this array to the end of the $customer_record array.

Array (

[0] =>

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

[1] =>

Array ( [0] => Sally [1] => Parisi [2] => 101 South Street [3] => Atlanta [4] => GA [5] => 30001 )

[2] =>

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

All the values were appended to the end of the array with just one code statement!

Note: We could also use array_push to add the Jake information shown in a previous example.

array_push($customer_record, array(‘Jake’ , ‘Boukari’ , ‘111 Peachtree Street’ , ‘Atlanta’ , ‘GA’ , 30011));

This would eliminate the need to use a subscript (2 was used in the previous Jake example).

Let’s take this example a step closer to the ‘real world’. One short-coming of this example is that the information is lost when the program ends. We can make a few changes to the code to read and save our array from a text file.

Note: In the ‘real world’ this information would probably be saved in a database. However, this example gives you a general idea of how easy it is to save information with PHP.

Example 2-4 - process_customer_array_twodim_saved.php

<?php

$customer_file = file_get_contents("customer_data.json");

$customer_record = json_decode($customer_file, TRUE);

$customer = filter_input_array(INPUT_POST);

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

array_push($customer_record, $customer_info);

print_r($customer_record);

file_put_contents("customer_data.json",json_encode($customer_record));

?>

A lot happens in Example 2-4. The PHP method file_get_contents will dump all the contents of a file into the property provided. The contents of the file customer_data.json are placed into the property $customer_file (which makes it an array).

$customer_record = json_decode($customer_file, TRUE);

In this statement the contents of $customer_file are converted from JSON format to PHP array format using the PHP function json_decode. The file itself contains JSON data. The array created is placed into the property $customer_record. This automatically turns $customer_record into a two-dimensional array (assuming that the information in the file is formatted correctly).

file_put_contents("customer_data.json",json_encode($customer_record));

After the html array is retrieved from the html form, added to the $customer_record array, and displayed, it is time to store the updated information. The PHP function file_put_contents will dump the contents of a property into a file. It will overwrite whatever is already in the file. It will also create the file if it does not exist.

However, remember it is assumed that JSON data is stored in the file. To convert the array into JSON format the PHP method json_encode is called. This converted JSON data is then stored in the file customer_data.json.

In just seven lines of code an array is populated from a file, data is retrieved from an html form and added to the array, and the data is then stored back into the file.

Let’s make one last improvement to this program. If the data contained within the file is not a valid JSON format, PHP will produce an error message. Let’s add some code to keep our program from crashing if the file is invalid or missing, or the data in the file not a valid JSON format.

Example 2-5 – process_customer_array_twodim_saved_ex.php

<?php

try

{

$customer_file = file_get_contents("customer_data.json");

$customer_record = json_decode($customer_file, TRUE);

$customer = filter_input_array(INPUT_POST);

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

array_push($customer_record, $customer_info);

print_r($customer_record);

file_put_contents("customer_data.json",json_encode($customer_record));

}

catch(Exception $e)

{

print "An Exception occurred. Message: " . $e->getMessage();

}

catch(Error $e)

{

print "An Error occurred. Message: " . $e->getMessage();

}

?>

In PHP 7, the try/catch blocks are used to capture Exceptions and Errors. Exceptions are ‘user’ exceptions that maybe raised by the program. For example, a validation method (such as validate_zip_code) determines if the zip code information received from the html form is in the proper format. If the information is not valid, the method can raise an exception for the calling program to handle. If this occurred the flow of the code would jump to a catch block handling exceptions (if there is one).

In Example 2-5, $e holds the Exception object. The object includes a getMessage method which holds the actual error message produced. The print statement would display the error message. User Exceptions are not usually considered to be fatal. They should be handled by the program and execution of the program should continue, if possible.

Errors are produced by the PHP environment. An error could be produced if the file accessed does not exist. Errors can also be produced if there are syntax errors in the program code. In PHP 7, Errors can be handled in a similar fashion as Exceptions. In this example, any error is caught by the catch block for errors. The Error object also include a getMessage method to display the error message. Unlike Exceptions, Errors are considered to be fatal. The program should be shut down when errors occur.

The use of both catch blocks in the example, will ensure that we capture all possible problems with executing this program and display the messages related to the problems that might occur.

Now let’s look at a quick MySQL database example.

Example 2-6 – process_customer_array_twodim_saved_mysqli.php


try

{

$mysqli = new mysqli("localhostorwebsite", "userid", "password", "database");

$query = "SELECT * FROM customers";

$result = $mysqli->query($query);

$customer_record = $result->fetch_all(MYSQLI_NUM);

$customer = filter_input_array(INPUT_POST);

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

array_push($customer_record, $customer_info);

print_r($customer_record);

$query = “INSERT INTO customers(first_name, last_name, address, city, state, zip_code) VALUES (“;

$query .= $customer_info[0] . “,” . $customer_info[1] . “,” . $customer_info[2] . “,”;

$query .= $customer_info[3] . “,” . $customer_info[4] . “,” . $customer_info[5] . “)”;

$result = $mysqli->query($query);

$mysqli->close();

}

catch(Exception $e)

{

print "An Exception occurred. Message: " . $e->getMessage();

}

catch(Error $e)

{

print "An Error occurred. Message: " . $e->getMessage();

}

?>

Example 2-6 provides a very simplified example using a MySQL database.

$mysqli = new mysqli("localhostorwebsite", "userid", "password", "database");

The first line connects to MySQL and the database (“database”) with the given userid and password. The first parameter should either include “localhost” or the URL address (or IP address) of the database location.

$query = "SELECT * FROM customers";

The second statement builds a SQL string to pull all the customers records from the database.

$result = $mysqli->query($query);

The third line executes the query and places the results in $result.

$customer_record = $result->fetch_all(MYSQLI_NUM);

The fetch_all method converts the database rows into a two dimensional array (with numeric subscripts). The array is placed into $customer_record.

The next several lines are the same as the previous example.

$query = “INSERT INTO customers(first_name, last_name, address, city, state, zip_code) VALUES (“;

$query .= $customer_info[0] . “,” . $customer_info[1] . “,” . $customer_info[2] . “,”;

$query .= $customer_info[3] . “,” . $customer_info[4] . “,” . $customer_info[5] . “)”;

After the information from the html form is attached to the $customer_record array (and displayed) a SQL INSERT string is created from the information gathered in the html form.

$result = $mysqli->query($query);

The query command then adds the record to the database.

$mysqli->close();

The close statement then closes the database connection. Any Exceptions or Errors are caught by the catch blocks.

There is no reason to reload all the records back into the database. In this example only the one record needs to be added to the current records.

Let’s revisit the foreach loop to display information contained in two-dimensional arrays.

$customer_record = array (

array(‘Pete’ , ‘Smith’ , ‘123 Main Street’ , ‘Atlanta’, ‘GA’, 30001),

array(‘Sally’ , ’Parisi’ , ‘101 South Street’ , ‘Atlanta’ , ‘GA’ , 30001)

);

foreach ($customer_record as $row)

{

foreach($row as $column_value)

{

Print $column_value . “ “;

}

}

foreach($customer_record as $row)

The first foreach statement contains the array name ($customer_record) and the row currently accessed by the loop ($row).

print_r($customer_record[]);

This is similar to only using one subscript when retrieving information from a two-dimensional array. The statement above will pull the current row (array) and display it. The outer foreach loop also pulls the current row (array) and places it in $row.

The first time the loop executes, it will be on row 0 (Pete). Each time flow of the program hits the bottom of the outer loop and then returns to the top, the foreach loop will move to the next row, until there are no more rows.

foreach($row as $column_value)

The internal loop moves through the value within each column for the row that has been selected by the outer foreach loop. $row contains all columns (values) in the current row. $column_value contains the contents of the current column. Each time the flow of the program hits the bottom of the inter loop and returns to the top of the inter foreach loop the next column is selected. When no more columns exist in the row, the loop ends.

When this occurs, the flow of the program will also drop to the bottom of the outside loop. This sends the flow back to the top of the outer loop, which retrieves the next row (if there is one).

print $column_value . “ “

The print statement contained inside the inter loop displays the values in column within each row.

The format used above does not allow us to retrieve the actual row subscript number (0, 1) or the column subscript number (0, 1, 2, 3, 4, 5). To have access to this information we must break the $row property into two parts. Currently $row is the actual array (row) that will be accessed. It does allow us access to the subscript. To access the subscript we must request both the row subscript and the values in the row using the following format.

foreach( $customer_record as $row => $row_array)

{

foreach( $row_array as $column => $column_value)

{

print "Row: $row Column: $column Value: $column_value ";

}

print “<br>”;

}

Row: 0 Column: 0 Value: Pete Row: 0 Column: 1 Value: Smith Row: 0 Column: 2 Value: 123 Main Street Row: 0 Column: 3 Value: Atlanta Row: 0 Column: 4 Value: GA Row: 0 Column: 5 Value: 30001

Row: 1 Column: 0 Value: Sally Row: 1 Column: 1 Value: Parisi Row: 1 Column: 2 Value: 101 South Street Row: 1 Column: 3 Value: Atlanta Row: 1 Column: 4 Value: GA Row: 1 Column: 5 Value: 30001

Row: 1 Column: 0 Value: Fred Row: 1 Column: 1 Value: Smith Row: 1 Column: 2 Value: 123 Main Street Row: 1 Column: 3 Value: Atlanta Row: 1 Column: 4 Value: GA Row: 1 Column: 5 Value: 30001

This style is commonly referred to as the $key => $value format. The loop above uses $row instead of $key and $row_array instead of $value. It also uses $column instead of $key and $column_value instead of $value. The programmer can use any name for the key and value properties.

The format becomes clear when looking at the print statement and the output from the print statement. It is clear that $row now contains the actual row subscript, $column contains the column subscript, and $column_value contains the value in the row and column specified.

foreach loops can also be used to populate an array with values. It is common practice to provide initial values in an array, especially if the array will be used in calculations. In chapter 1, we talked about the possibility that an array, in some program languages, could contain a NULL value. If an attempt is made to do a calculation on a position in an array that contains a NULL value, an Error will be thrown. This can be avoided by providing initial values.

foreach( $customer_record as $row => $row_array)

{

foreach( $row_array as $column => $column_value)

{

$customer_record[$row][$column] = "default";

}

}

The code above will place “default” in every position in the array. Remember, in many situations, the loading of initial values in a PHP array is not necessary because the array positions can be created and populated with actual values at the same time. Some programmers, chose to still initialize values to be consistent with the logic used in other programming languages.

PHP also provides the method array_fill which will accomplish the same task as the previous example.

$customer_record = array_fill(0, 3, array_fill(0, 5, “default”));

The statement will create and fill each position in a $customer_record two-dimensional array with the value “default”.

The array_fill syntax is:

Array name = array_fill(first subscript in array, last subscript in array, value used to fill array);

In the example, four rows are created (0, 1, 2, 3) as indicated by 0, 3. Each row contains an array (as shown by the third position creating another array) with six columns (0, 1, 2, 3, 4, 5) as indicated by 0, 5. The limitation of using this method is that we need to know the initial size of the array. Of course, we can always add more rows and columns as needed.

$customer_record = array_fill(0, 5, “default”);

For a one dimensional array, we include the starting subscript (0), the ending subscript (5), and the value we want to place in each position (“default”).

The same logic shown in this chapter can be used for arrays that have more than two dimensions. The number of subscripts is determined by the number of dimensions, as is the number of foreach loops.

$square_array[$height][$length][$width] = 123;

foreach( $square_array as $height => $height_array)

{

foreach( $height_array as $length => $length_array)

{

foreach( $length_array as $width => $width_value)

{

print $width_value;

$square_array[$height][$length][$width]= 345;

}

}

}

123

The loop above will traverse through the three-dimensional array $square_array to display the value(s) in the array and then change the value(s) for each position to 345.

Deleting

Example 1-8 deletesubscript.php

$customer_record = array (

array('Pete' ,'Smith' ,'123 Main Street' ,'Atlanta','GA', 30001),

array('Sally' ,'Parisi' ,'101 South 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 previously demonstrated the removal of a subscript within a one-dimesional array. However, no changes (except for the array itself) are needed if the user wants to delete a row from a two-dimensional array. In this example the Sally array would be removed.

If we are using a two dimensional array and want to remove one value from one of the rows, we can make a minor adjustment to our example.

Example 2-7 deletesubscript2dim.php

$customer_record = array (

array('Pete' ,'Smith' ,'123 Main Street' ,'Atlanta','GA', 30001),

array('Sally' ,'Parisi' ,'101 South Street' ,'Atlanta' , 'GA' , 30001)

);

declare(strict_types=1);

function delete_array_value(int $first_subscript, int $second_subscript)

{

unset($customer_record[$first_subscript][$second_subscript);

}

delete_array_value(1,1);

In this example, after adding a second subscript, ‘Parisi’ would be removed.

Updating & Inserting

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

$customer_record = array (

array('Pete' ,'Smith' ,'123 Main Street' ,'Atlanta','GA', 30001),

array('Sally' ,'Parisi' ,'101 South Street' ,'Atlanta' , 'GA' , 30001)

);

declare(strict_types=1);

function update_array_value(int $subscript, $value)

{

$customer_record[$subscript] = $value;

}

$temp_array = array('Peter' ,'Smith' ,'1234 Main Street' ,'Atlanta', 'GA', 30001);

update_array_value(0, $temp_array);

This example totally replaces the Pete array with a Peter array. 0 is passed into $subscript and the Peter array is passed into $value when the method is called. The method then replaces the contents of position 0 with the values in the Peter array. Actually it will also insert the array if the position does not currenty exist in the array.

If we just want to change one value in the array, we can make a slight adjustment.

$customer_record = array (

array('Pete' ,'Smith' ,'123 Main Street' ,'Atlanta','GA', 30001),

array('Sally' ,'Parisi' ,'101 South Street' ,'Atlanta' , 'GA' , 30001)

);

declare(strict_types=1);

function update_array_value(int $first_subscript, int $second_subscript, $value)

{

$customer_record[$first_subscript][$second_subscript] = $value;

}

update_array_value(0, 0, “Peter”);

This example would replace Pete with Peter. 0 is passed into $first_subscript. 0 is also passed into $second_subscript. Peter is passed into $value when the method is called. The update method then replaces the contents of position 0,0 with Peter. Again, if the position does not exist, it will insert the value into the position.

Let’s make a slight change to the chapter 1 example which combined the ability to insert and update.

If we are using an array with numeric subscript, we can insert into a missing subscript. Also, we can append our new values to the end of the array as we have done in several examples.

$customer_record = array (

array('Pete' ,'Smith' ,'123 Main Street' ,'Atlanta','GA', 30001),

array('Sally' ,'Parisi' ,'101 South Street' ,'Atlanta' , 'GA' , 30001)

);

declare(strict_types=1);

function update_array_value( $value, int $first_subscript = -1, int $second_subscript = -1)

{

if( $first_subscript != -1 && $second_subscript != -1)

{ $customer_record[$first_subscript][$second_subscript] = $value; }

else if ($first_subscript != -1)

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

else

{ array_push($customer_record, $value); }

}

$temp_array = array('Jackie' ,'Smith' ,'123 Main Street' ,'Atlanta','GA', 30001);

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

update_array_value($temp_array, 1);

update_array_value($temp_array);

This new version of the update method allows us to insert individual values into any missing positions (or actually replace values from current positions). If both positions are provided (1,6) the method will use both positions to update a value (in this example, the phone number is actually added to the end of the Sally array). If only one position is provided, the second position ($second_subscript) will default to -1. If the array is two-dimensional (as shown here) an array could be passed to completely replace the existing array (row).

update_array_value($temp_array, 1);

The second call to this method will replace the Sally array with the Jackie array.

update_array_value($temp_array);

If no positions are passed, the method will set $first_subscript and $second_subscript to -1. This will cause the method to execute the else part of the if statement which will use array_push to add the array to the end of the existing array.

This update method actually also allows us to also input values in existing positions because the only difference between insert and update is whether there is actually something already in the position.

Every program language has the ability to create arrays for even more dimensions. However, programs become less efficient with each additional dimension. With additional dimensions the operating system must build additional tables in memory to keep track of the location of the data. The logic quickly becomes more complex reducing efficiently. Also it becomes more difficult for humans to relate beyond three or four dimensions (height, width, length, time???). This is why you rarely will see programs that contain arrays with more than three (or four) dimensions.

We have come a long way in a short period of time. Let’s take another break and do some practice exercises.

Exercises

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

1. Adjust Exercise #1 from Chapter 1 to pull book information from a file, create a two dimensional array from the file, accept information about a book from an html form, add the information to the array, and store the information. Use the code from Example 2-4 or Example 2-5 to help you.

Before you can read from a file there needs to be records in the file. Add the code to save the array into the file first. Then run the program. Verify that the information was saved properly in the file. Then add code to read from the file.

2. Compare the PHP code used in this chapter to create and update two-dimensional arrays to another programming language. Which is easier and more efficient? Why? If you don’t have other language examples, search the web using the language name and arrays. Such as:

“Creating and updating multi-dimensional arrays in Java”