Associative and Object 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 3. Associative and Object Arrays

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

Define and describe the advantages in using associative arrays

Create a simple PHP associative array

Save values into a simple PHP associative array

Display values contained in simple PHP associative array

Create a multi-dimensional PHP associative array

Save values into a multi-dimensional PHP associative array

Display values contained in a multi-dimensional associative array

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

Validate values before placing them into an associative array

Define and describe the advantages in using an object array

Create a simple PHP object array

Save values into a simple PHP object array

Add values from an html form into a PHP object array

Display values contain in a simple PHP object array

Validate values before placing them into a simple PHP object array

So far all the examples have include arrays that user numeric subscripts. They are not very descriptive. For example:

print customer_record[5];

If we ran across this statement in program code, we could determine that the array contains a customer’s record. However, what the heck is in position 5? We would not know unless we viewed some actual data in the array itself. PHP allows developers to use alphabetic characters instead of numbers for subscripts.

print customer_record[‘zip_code’];

In this example, the subscript is now much more readable. We now know that only zip code information will reside in this area of the array. Arrays that contain alphabetic characters in PHP are commonly called Associative Arrays.

Some students get lost when learning about Associative Arrays. However, there is no reason to panic. You have already seen them used in every example in this book!!

What?

Yes, remember, it was mentioned in chapter one that all arrays are the same in PHP. All arrays are Associative Arrays. The only difference between what we discussed before and now is what is placed in the subscript. Recall Example 1-4:

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]";

?>

The subscripts in this example are 0, 1, 2, 3, 4, and 5. That is not very descriptive. Instead, we can use words.

Example 3-1

<?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[“first_name”] = validate_first_name($_POST['first_name']);

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

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

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

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

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

print "Your name is $customer_record[‘first_name’]

$customer_record[‘last_name’]. You live at $customer_record[‘address’],

$customer_record[‘city’], $customer_record[‘state’],

$customer_record[‘zip_code’]";

?>

If we replace each numerical subscript with a more meaningful alphabetic subscript, we produce a program that is much more readable. For example, we see that the “first_name” value is accepted from the html form via the $_POST method. The value in the property is validated by the validate_first_name method. If it is valid, the information is placed into the $customer_record array at a location called (you guessed it!) first_name. A similar process happens with all the other data retrieved.

Note: Notice that the print statement uses single quotes around the subscript name (such as ‘first_name’) instead of double quotes. You cannot embedded double quotes inside of double quotes (which contain the complete string to be printed). You can, in many cases but not all, use single quotes instead.

Let’s take a look at another previous example.

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));

?>

In Example 2-4, a two dimensional array is retrieved from a file, appended with information from an html form, and saved into the original file. This array used numerical subscripts. We only need to change one line to allow this code to handle an associative array that would exist in the customer_data.json file.

Example 3-2 - process_customer_associate_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);

list(

$customer_info['first_name'], $customer_info['last_name'],

$customer_info['address'], $customer_info['city'],

$customer_info['state'], $customer_info['zip_code']

) = 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));

?>

The PHP list is a language construct that can be used to assign values to multiple properties (variables) at the same time. Before PHP 7, the values were actually assigned in reverse order. PHP 7 assigns them in the order presented. Since we are using actual alphabetic values for our subscripts and not numerical values, the order does not matter.

list(

$customer_info['first_name'], $customer_info['last_name'],

$customer_info['address'], $customer_info['city'],

$customer_info['state'], $customer_info['zip_code']

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

This example code would work correctly in either order. The value from position 0 in the customer_record array (which came from the html form) will be placed into $customer_info[‘first_name’]. The value in position 1 will be placed in$customer_info[‘last_name’]. The process would continue for the number of positions in the customer_record array.

The number of properties in the list statement should be the same number as the positions in the array. This example should include the previous try/catch blocks shown to capture any errors if there is not as many positions in the array as expected. The try/catch block would also handle any problems with the file itself.

Array (

[0] =>

Array ( [first_name] => default [last_name] => default [address] => default [city] => default [state] => default [zip_code] => 10001 )

[1] =>

Array ( [zip_code] => 11111 [state] => af [city] => ad [address] => aq [last_name] => as [first_name] => aa )

)

By using associate arrays we don’t have to worry about the order in which values are saved. In the above example, the two arrays are saved in reverse order. However, we access the values by the alphabetic subscript names, not position. print $customer_record[0][‘first_name’] will display the value in that location (default) no matter where it actually is located in the array.

Let’s look at the changes needed to retrieve and save the information in a MySQL database.

Example 3-3 – process_customer_associate_array_twodim_mysqli.php

try

{

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

$query = "SELECT * FROM customers";

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

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

$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[first_name’] . “,” . $customer_info[‘last_name’] . “,”;

$query .= $customer_info[‘address’] . “,” . $customer_info[‘city’] . “,” . $customer_info[‘state’] ;

$query . = “,” . $customer_info[‘zip_code’] . “)”;

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

$mysqli->close();

}

catch(Exception $e)

{

// … no changes in the try blocks

Very few changes are needed when handling associative arrays with MySQL.

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

The result set identifier must be changed from returning a numeric array (MYSQLI_NUM), as shown in the previous chapter, to return an associative array (MYSQLI_ASSOC).

$query .= $customer_info[first_name’] . “,” . $customer_info[‘last_name’] . “,”;

$query .= $customer_info[‘address’] . “,” . $customer_info[‘city’] . “,” . $customer_info[‘state’] ;

$query . = “,” . $customer_info[‘zip_code’] . “)”;

The indexes used with each position in the customer_info array must also be changed from numeric (0, 1, 2, 3, 4, 5) to alphabetic (‘first_name’, ‘last_name’, ‘address’, ‘city’, ‘state’, ‘zip_code’).

$customer_record = array (

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

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

);

We produce the expected results with just two line changes.

$customer_record = array (

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

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

);

In chapter 2 we declared an array and its values using the syntax shown above. When using the same syntax to declare an associate array we must specify the index (alphabetic subscript name) and the value together.

This is when it can get a little confusing. However, we will keep it as simple as possible.

$customer_record = array (

array('first_name' => 'Pete' , 'last_name' => 'Smith' , 'address' => '123 Main Street' , 'city' => 'Atlanta', 'state' => 'GA', 'zip_code' => 30001),

array('first_name' => 'Sally' , 'last_name' => 'Parisi' , 'address' => '101 South Street' , 'city' => 'Atlanta' , 'state' => 'GA' , 'zip_code' => 30001)

);

print_r($customer_record);

Array (

[0] =>

Array ( [first_name] => Pete [last_name] => Smith [address] => 123 Main Street [city] => Atlanta [state] => GA [zip_code] => 30001 )

[1] =>

Array ( [first_name] => Sally [last_name] => Parisi [address] => 101 South Street [city] => Atlanta [state] => GA [zip_code] => 30001 )

)

To add an alphabetic subscript to this example we use the same syntax we discovered in foreach loops. key => value is used to define each position in the array. The key is the subscript name (‘first_name’). The value is the information placed in the location (‘Pete’).

‘first_name’ => ‘Pete’

'last_name' => 'Smith'

'address' => '123 Main Street'

'city' => 'Atlanta'

'state' => 'GA'

'zip_code' => 30001

We can then retrieve a value using its subscript name.

print $customer_record[0][‘last_name’];

Smith

Did you notice that the example did not change the subscript for the rows ([0],[1])?

The example did not specify any names for the rows. Remember that all arrays in PHP are the same. There is nothing wrong with mixing numeric and alphabetic subscripts (as shown) in this array.

We can, however, provide a names for our rows if needed.

$customer_record = array (

'first_customer' =>

array('first_name' => 'Pete' , 'last_name' => 'Smith' ,

'address' => '123 Main Street' , 'city' => 'Atlanta',

'state' => 'GA', 'zip_code' => 30001),

'second_customer' =>

array('first_name' => 'Sally' , 'last_name' => 'Parisi' ,

'address' => '101 South Street' , 'city' => 'Atlanta' ,

'state' => 'GA' , 'zip_code' => 30001)

);

Array (

[first_customer] =>

Array ( [first_name] => Pete [last_name] => Smith

[address] => 123 Main Street [city] => Atlanta

[state] => GA [zip_code] => 30001 )

[second_customer] =>

Array ( [first_name] => Sally [last_name] => Parisi

[address] => 101 South Street [city] => Atlanta

[state] => GA [zip_code] => 30001 ) )

To add an alphabetic name to our rows, we, again, use the same key => value syntax. The only difference is that the value is actually an array (the row).

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

{

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

{

print "Row: $row Column: $column Value: $column_value <br>";

}

print “<br>”;

}

Row: first_customer Column: first_name Value: Pete

Row: first_customer Column: last_name Value: Smith

Row: first_customer Column: address Value: 123 Main Street

Row: first_customer Column: city Value: Atlanta

Row: first_customer Column: state Value: GA

Row: first_customer Column: zip_code Value: 30001
Row: second_customer Column: first_name Value: Sally

Row: second_customer Column: last_name Value: Parisi

Row: second_customer Column: address Value: 101 South Street

Row: second_customer Column: city Value: Atlanta

Row: second_customer Column: state Value: GA

Row: second_customer Column: zip_code Value: 30001

There are no changes needed to the foreach loops shown previously to display or change values in an associative array.

Why?

Again, all PHP arrays are the same. They have the same logic. Numeric, alphabetic, or a combination of both types of subscripts does not make a major difference in how they are used.

Deleting

Let’s return to one of our examples from chaper 2.

Example 2-7 deletesubscript2dim.php

$customer_record = array (

array(‘first_name’ =>'Pete' ,’last_name’ =>'Smith' ,’address’ =>'123 Main Street' ,’city’ => 'Atlanta', ‘state’ =>'GA', ‘zip_code’ =>30001),

array(‘first_name’ =>'Sally' ,’last_name’ =>'Parisi' ,’address’ =>'101 South Street' ,’city’ => 'Atlanta' , ‘state’ =>'GA' , ‘zip_code’ => 30001)

);

declare(strict_types=1);

function delete_array_value(int $first_subscript, string $second_subscript)

{

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

}

delete_array_value(1,’last_name’);

The same exact logic can be used to remove a value (or row) from an associate array. The only change required is to change the data type accepted into the function from int to string. We could also just remove the data type restrictions and the method would work for any array.

Updating & Inserting

Actually we have already shown several examples on updating values in arrays in the previous chapters. Let’s take a quick look at the small amount of changes need to handle associative arrays.

$customer_record = array (

array(‘first_name’ =>'Pete' ,’last_name’ =>'Smith' ,’address’ =>'123 Main Street' ,’city’ => 'Atlanta', ‘state’ =>'GA', ‘zip_code’ =>30001),

array(‘first_name’ =>'Sally' ,’last_name’ =>'Parisi' ,’address’ =>'101 South Street' ,’city’ => 'Atlanta' , ‘state’ =>'GA' , ‘zip_code’ => 30001)

);

declare(strict_types=1);

function update_array_value(int $subscript, $value)

{

$customer_record[$subscript] = $value;

}

$temp_array = array(‘first_name’ =>'Pete' ,’last_name’ =>'Smith' ,’address’ =>'123 Main Street' ,’city’ => 'Atlanta', ‘state’ =>'GA', ‘zip_code’ =>30001);

update_array_value(0, $temp_array);

As shown before, this example totally replaces the Pete array with a Peter array. 0 is still passed into $subscript because no name was provided for the arrays that hold records.

$customer_record = array (

'first_customer' =>

array('first_name' => 'Pete' , 'last_name' => 'Smith' ,

'address' => '123 Main Street' , 'city' => 'Atlanta',

'state' => 'GA', 'zip_code' => 30001),

'second_customer' =>

array('first_name' => 'Sally' , 'last_name' => 'Parisi' ,

'address' => '101 South Street' , 'city' => 'Atlanta' ,

'state' => 'GA' , 'zip_code' => 30001)

);

declare(strict_types=1);

function update_array_value(string $subscript, $value)

{

$customer_record[$subscript] = $value;

}

$temp_array = array(‘first_name’ =>'Pete' ,’last_name’ =>'Smith' ,’address’ =>'123 Main Street' ,’city’ => 'Atlanta', ‘state’ =>'GA', ‘zip_code’ =>30001);

update_array_value(‘first_customer’, $temp_array);

If we do name the rows, then, except for the array itself, only one slight change it needed. The data type for the subscript either needs to be changed to string or removed altogether. Also, the subscript passed into the function needs to give the name of the array to be replaced,

Both of these examples would replace the array containing Pete with the array containing Peter. Actually it will also insert the array if the position does not currenty exist in the array.

Let’s take a look at replacing one value.

$customer_record = array (

array(‘first_name’ =>'Pete' ,’last_name’ =>'Smith' ,

’address’ =>'123 Main Street' ,’city’ => 'Atlanta',

‘state’ =>'GA', ‘zip_code’ =>30001),

array(‘first_name’ =>'Sally' ,’last_name’ =>'Parisi' ,

’address’ =>'101 South Street' ,’city’ => 'Atlanta' ,

‘state’ =>'GA' , ‘zip_code’ => 30001)

);

declare(strict_types=1);

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

{

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

}

update_array_value(0, ‘first_name’, “Peter”);

Only two minor changes (besides the array itself), are needed from the original example from chapter 2. The data type of the second subscript is changed to string and the string subscript (first_name) is passed into the method. As we have seen before this example would replace Pete with Peter. Again, if the position does not exist, it will insert the value into the position.

If we are providing alphabetic rows, we only need to change the array, the data type of the first subscript, and the value passed in for the first subscript.

$customer_record = array (

'first_customer' =>

array('first_name' => 'Pete' , 'last_name' => 'Smith' ,

'address' => '123 Main Street' , 'city' => 'Atlanta',

'state' => 'GA', 'zip_code' => 30001),

'second_customer' =>

array('first_name' => 'Sally' , 'last_name' => 'Parisi' ,

'address' => '101 South Street' , 'city' => 'Atlanta' ,

'state' => 'GA' , 'zip_code' => 30001)

);

declare(strict_types=1);

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

{

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

}

update_array_value(‘first_customer’, ‘first_name’, “Peter”);

Let’s revisit the method that combines these ideas.

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. With associate arrays the actual physical location of the information in the array does not matter since we are referencing our information using alphabetic subscripts.

$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, string $first_subscript = “none”, string $second_subscript = “none”)

{

If( $first_subscript != “none” && $second_subscript != “none”)

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

else if ($first_subscript != “none”)

{ $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”, “second_customer”, “phone_number”);

update_array_value($temp_array, “second_customer”);

update_array_value($temp_array);

A mentioned before, this update method allows us to insert individual values into any missing positions (or actually replace values from current positions). If both positions are provided (“second_customer”, “phone_number”) the method will use both positions to update a value (in this example, the phone number is actually added with a subscript of phone_number to the end of the Sally array). If only one position is provided, the second position ($second_subscript) will default to “none”. 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, “second_customer”);

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 “none”. 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. A numeric subscript (0) will be created to hold the new row.

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.

Hopefully you can now see that associative arrays are a great tool provided by PHP. Code using associative arrays is much more readable. There is also no efficiency difference because all arrays in PHP are stored in memory in the same manner.

Object Arrays

Let’s take a brief look at an Object Array. If you are not familiar with Object Oriented Programming, you can skip this section without it causing you any difficulty in the next chapter.

<?php

class Customer

{

// all code placed here

}

?>

PHP classes are created using the class keyword followed by a class name. Class names should be indicated with a capital first letter (Customer). All code is then encapsulated (contained) when the {}. If the class is contained in a separate file, the filename should match the class name (Customer.php).

class Customer

{

private $first_name = “NFN”;

private $last_name = “NLN”;

private $address = “NA”;

private $city = “NC”;

private $state = “NS”;

private $zip_code = “NZC”;

}

Properties are protected using the private keyword. Each property shown has been given a default value. However, the value will be changed when the user ‘sets’ the property. Set methods are used to change property values. Get methods are used to retrieve property values.

declare(strict_types=1);

function set_first_name(string $value)

{

if((strlen($value) > 0) && (strlen($value) < 21))

{

$this->first_name = $value;

}

else

{

throw new Exception(“Invalid First Name”);

}

}

Using set methods allow the ability to verify the data before storage, in a similar manner to the verify methods previously discussed. PHP 7 also allows the ability to restrict the data types accepted into the methods (int, string, float, bool), using the declarestatement and specifying the data type expected.

function set_first_name(string $value)

In this example, the function expects a string to be passed into $value from the calling program.

if((strlen($value) > 0) && (strlen($value) < 21))

If a string is passed, the method will determine if the value accepted has a length between 1 and 20.

$this->first_name = $value;

If the string is between 1 and 20 characters it is saved in the property first_name.

What happens if the value is not valid?

In this example an exception will be thrown if the value is not a string. However, an exception is not thrown if the length of the string is not 1 to 20 characters. Since a default value (NFN) has been originally placed in the property, that value is retained and the program continues.

declare(strict_types=1);

function get_first_name() : string

{

return $this->first_name;

}

PHP 7 can also restrict the type of data returned from a get method using a similar format.

return $this->first_name;

Set methods do not accept values. They only return values. There is no need to a complete a validation of the information that is retrieved from the first_name property. The value in the property is assumed to be valid and is retrieved, then passed back to the calling program. If the value in first_name is not a string, an exception will be raised.

class Customer

{

private $first_name = “NFN”;

private $last_name = “NLN”;

private $address = “NA”;

private $city = “NC”;

private $state = “NS”;

private $zip_code = “NZC”;

declare(strict_types=1);

function __construct(string $value1, string $value2,

string $value3, string $value4, string $value5,

int $value6)

{

$this->set_first_name($value1);

$this->set_last_name($value2);

$this->set_address($value3);

$this->set_city($value4);

$this->set_state($value5);

$this->set_zip_code($value6);

}

declare(strict_types=1);

function set_first_name(string $value)

{

if((strlen($value) > 0) && (strlen($value) < 16))

{ $this->first_name = $value ;}

else

{ throw new Exception(“Invalid First Name”); }

}

function set_last_name(string $value)

{ if((strlen($value) > 0) && (strlen($value) < 21))

{ $this->last_name = $value; }

else

{ throw new Exception(“Invalid Last Name”); }}

function set_address(string $value)

{ if((strlen($value) > 0) && (strlen($value) < 31))

{ $this->address = $value; }

else

{ throw new Exception(“Invalid Address”); }}

function set_city(string $value)

{ if((strlen($value) > 0) && (strlen($value) < 21))

{ $this->city = $value; }

else

{ throw new Exception(“Invalid City”); }}

function set_state(string $value)

{ if((strlen($value) > 0) && (strlen($value) < 3))

{ $this->state = $value; }

else

{ throw new Exception(“Invalid State”); }}

function set_zip_code( $value)

{ if(($value >= 11111) && ($value <= 99999))

{ $this->zip_code = $value; }

else

{ throw new Exception(“Invalid Zip Code”); }}

function get_first_name() : string

{ return $this->first_name; }

function get_last_name() : string

{ return $this->last_name; }

function get_address() : string

{ return $this->address; }

function get_city() : string

{ return $this->city; }

function get_state() : string

{ return $this->state; }

function get_zip_code()

{ return $this->zip_code; }

}

}

The class shown above provides a basic structure for storing the customer information.

function __construct(string $value1, string $value2, string $value3, string $value4,

string $value5, int $value6)

A constructor method is shown which accepts all values when the object is created. The constructor passes the values into set methods to validate the data before it is stored. Using this structure an object array can be declared to hold all customer objects needed.

We can now pass all information for once customer with just one line of code.

$customer_record[] = new Customer("Pete”, "Smith", "123 Main Street", "Atlanta", "GA", 30001);

Position zero of the customer_record array would now point to an object holding all of the information for Pete.

print $customer_record[0].get_first_name();

Pete

Retrieving information from the object array just requires calling the correct get method.

$customer_record[0].set_first_name(‘Peter).

Changing values just requires calling the correct set method.

If we make a slight change to the constructor method shown previously we can pass html data into our object array with very little code.

function __construct($value)

{

$this->set_first_name($value[0]);

$this->set_last_name($value[1]);

$this->set_address($value[2]);

$this->set_city($value[3]);

$this->set_state($value[4]);

$this->set_zip_code($value[5]);

}

Instead of expecting multiple individual properties passed into the constructor, this version accepts an array and sets the properties based on the positions in the array.

We could also use an associative array by just changing the subscripts ($value[‘first_name’];).

This new constructor makes passing an html array very easy. We can just change one line from our previous example.

Example 3-3 customer_object.php

<?php

// … Customer class structure goes here

$customer = filter_input_array(INPUT_POST);

$customer_record[] = new Customer($customer["customer_record"]);

var_dump($customer_record);

$customer_record[] = new Customer($customer["customer_record"]);

The customer_record html array is pulled from the customer array which was populated by values entered by the user in the html form. A Customer object is created. The customer_record array is passed into the constructor of the Customer object.

function __construct($value)

The constructor renames the array as $value.

set_first_name($value[0]);

set_last_name($value[1]);

set_address($value[2]);

set_city($value[3]);

set_state($value[4]);

set_zip_code($value[5]);

The values in each position of the $value array are then passed into set methods to populate the new Customer object properties. Finally the Customer object is attached to the PHP $customer_record array at position 0 (or the next available position).

All of this action takes place because of the one line!

array(1)

{ [0]=> object(Customer)#1 (6)

{ ["first_name":"Customer":private]=>

string(4) "fred"

["last_name":"Customer":private]=>

string(5) "smith"

["address":"Customer":private]=>

string(15) "123 Main Street"

["city":"Customer":private]=>

string(8) "Marietta"

["state":"Customer":private]=>

string(2) "GA"

["zip_code":"Customer":private]=>

string(5) "11111" } }

In the example, var_dump was used, instead of print_r, to provide a more detailed view of the array. We can see that the Customer object is attached at position 0 of the customer_record array with a first_name (“fred”) and last_name (“smith”).

There is much more we could discover about object arrays. However, the intent is just to get your feet wet.

Why would we use object arrays instead of associative arrays?

One good example is provided in the gaming industry. In many games, once the user obtains a certain expert level, they are invited to play a bonus round. In order to jump to the bonus round all information related to the current level the user has obtained must be saved. Everything on the screen (including the aliens) are objects. These objects can be temporarily saved to an object array while the user plays the bonus round. When the user has completed the round, the objects can be retrieved from the array and placed back into their original positions on the screen. Each object would include properties to indicate their last location to complete this process.

We are already done discussing Associative and Object Arrays. As we have seen, only a few coding changes are need to use associative arrays instead of numerical arrays. Associative arrays allow us to create much more readable code syntax. We no longer need to try to figure out what $customer_record[0] contains. We can see that $customer_record[‘first_name’] will hold a first name.

Let’s try an exercise before the next chapter.

Exercises

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

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

Before you can read from a file there needs to be associative JSON 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. What other programming languages have Associate Arrays? Give an example of the syntax to create one in another language.