PHP Arrays (Best Tutorial 2019)

PHP Arrays

PHP Array Best Tutorial 2019

An array is nothing more than a container of multiple properties. 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.

 

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 to determine where 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.

PHP Array

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

Example  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]."; print "You live at $customer_record[2], $customer_record[3]"; 
print " $customer_record[4], $customer_record[5]"; ?>

 

In Example, the individual records are replaced with locations within the array $customer_record to store the values retrieved. In most programming languages, array subscripts must be numbered beginning with zero.

 

Unlike many other languages, PHP allows us to dynamically create our array locations when needed This allows us to store and revive values in an array in a similar way of storing and retrieving values in properties.

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

Example process_customer_record.php



accepts information from example1.HTML

//

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

$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]."; print "You live at $customer_record[2], $customer_record[3],"; print "$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.

 

Notice, in Example, 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 in the following 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 positionIf a position is skipped in a PHP array, that position merely does not exist.

print_r($customer_record);

Array ( [0] => Steve [2] => Scientist [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 seen or been taught to use the for loop 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 preceding example) and automatically retrieve 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 (Steve). 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 (Scientist) and continue until all positions in the array have been printed.

 

Steve Scientist 123 Main Street Atlanta GA 30001

 

The foreach loop makes retrieving values from PHP arrays easy

 PHP arrays easy

Using this loop will eliminate any possibility of trying to retrieve values from nonexistent positions in the array and also 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(‘Steve’, ‘Scientist’, ‘123 Main Street’, ‘Atlanta’, ‘GA’, ‘30001’); print_r($customer_record);

Array ( [0] => Steve [1] => Scientist [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 (six) 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] = ‘Thesis’;
print_r($customer_record);
Array ( [0] => Thesis [1] => Scientist [2] => 123 Main Street [3] => Atlanta [4] => GA [5] => 30001 )
As you can see, Steve is replaced by Thesis 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] => Thesis [1] => Scientist [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 preceding example, 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 an 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] => Thesis [1] => Scientist [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 blog.

$json = json_encode($customer_record);

print_r($json);

["Thesis","Scientist","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

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 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, 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 customer’s first name) is now placed into customer_record[0].

 

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

Example  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]. "; print "You live at $customer_record[2], $customer_record[3],"; print "$customer_record[4], $customer_record[5]"; ?>

As you can see from Example 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 fewer 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 to 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  $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

Deleting Array

 

Array (

[0]

=> Steve [1] => Scientist [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 preceding.

 

If we were to remove the second value ([1]), the textbook 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]

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

)

The loop would update the array to something similar to the preceding 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  deletesubscript.php

declare(strict_types=1);
function delete_array_value(int $subscript)
{
$customer_record =
array('Thesis' ,'Scientist' ,'123 Main Street' ,'Atlanta','GA', 30001); unset($customer_record[$subscript]);
}
delete_array_value(1);

The example 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 Scientist from the array. The array would now contain

$customer_record =
array('Thesis','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] => Thesis
[2]
=> 123 Main Street
[3]
=> Atlanta
[4]
=> GA
[5]
=> 30001
}

 

Updating & Inserting Array

Updating & Inserting Array

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

 

Example  insert.php

function insert_array_value( $value )

{

$customer_record =

array('Thesis' ,'Scientist' ,'123 Main Street' ,'Atlanta','GA', 30001); array_push($customer_record, $value);

}

insert_array_value(‘770-777-7777’);

 

In Example, 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  update.php

declare(strict_types=1);
function update_array_value( int $position, $value )
{
$customer_record =
array('Thesis' ,'Scientist' ,'123 Main Street' ,'Atlanta','GA', 30001); $customer_record[$position] = $value;
}
update_array_value(0, ‘Thesis_r');

 

In Example, 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 update_insert_value.php

declare(strict_types=1);
function update_array_value( $value, int $subscript = -1)
{
$customer_record =
array('Thesis' ,'Scientist' ,'123 Main Street' ,'Atlanta','GA', 30001);
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("Thesis", 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 this statement, 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 in position six. update_array_value(“Thesis”, 0);

 

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

 

As you will see frequently, once you get used to using arrays, you will find the amount of code needed to process the information is much less. The example has only four executable statements. 

 

This demonstrates that using arrays is more efficient than using individual properties. Arrays provide us the ability to expand (or contract) their size and allow us to easily adjust the data types stored.

 

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

 

[Note: You can free download the complete Office 365 and Office 2019 com setup Guide for here]

 

Multidimensional Arrays

Multidimensional Arrays

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

  • Define and describe the advantages of using multidimensional arrays
  • Compare a table with a multidimensional array
  • Create a multidimensional PHP array
  • Save values into a multidimensional PHP array
  • Display values in a multidimensional array
  • Add values from an HTML form into a multidimensional array
  • Validate values before placing them into a multidimensional 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 blog 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 to a particular individual component, such as a customer. In order to hold all of a customer’s 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.

 

Multidimensional arrays work in a similar way. A customer’s information is stored in a ‘record. In our previous example, all of the information related to Steve Scientist 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.

 

The answer lies in how the information is stored in memory. The operating system stores two-dimensional arrays by row. The rows are kept intact because everything in a row is related.

 

The row information is placed in memory locations that are contiguous to each other (next to each other). Other rows are not necessarily stored in memory next to previous rows. This allows 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. 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 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 saves the next row of information (possibly at a completely different location in memory).

 

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

print $customer_record[0];

 

we discovered that the preceding statement would print out the first name of the customer (‘Thesis’). 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 row (1), and the second subscript indicates column (0). If Table 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] = "Thesis";
$customer_record[0][1] = "Scientist";
$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] => Thesis
[1]
=> Scientist
[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 preceding information 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 first Array contains the information about Thesis Scientist. The second Array contains information about Sally Parisi.

 

In PHP, two-dimensional arrays are actually individual one-dimensional arrays held together by an array that surrounds them.

 Arrays

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 Thesis information to the array that contains the Sally information). One way we can do this is by using a counting variable.

 

Example  process_customer_twodim.php

<?php $I=-1; $customer_record[++$I][]='Thesis'; 
$customer_record[$I][]='Scientist'; 
$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, 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 Thesis. The remaining values for Thesis 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 Thesis or Sally array.

 

However, this is not the most efficient way! This is 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[][] = ‘Thesis’;)?

 

Each value for Thesis and Sally would end up with its own array and only one subscript. Each of the two subscripts would increment each time.

 

Download Example 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('Thesis' , 'Scientist' , '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 code to create. It produces the same results as Example. You do need to be careful to include all the required commas as shown in the preceding. 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] = 'Thesis';
$customer_record[0][6] ='770-770-7777';
$customer_record[2] =
array('Jake' , 'Boukari' ,'111 Peachtree Street' , 'Atlanta' ,'GA' , 30011);
Array (
[0] =>
Array ( [0] => Thesis [1] => Thesis_r [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 Thesis with Thesis_r). We are able to add another value to the array containing Thesis_r information (the array now contains his phone number).

 

We were also able to add a completely 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

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.

The answer is YES!

Example

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 is to change the name of the PHP program called (process_customer_array_twodim.php).

Example

process_customer_array_twodim.php
<?php $customer_record=array ( array('Thesis' , 'Scientist' , '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 , a two-dimensional array ($customer_record) is declared. 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 attaches this array to the end of the $customer_record array.
Array (
[0] =>
Array ( [0] => Thesis [1] => Scientist [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] => Steve [1] => Scientist [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 shortcoming 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 using 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 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));

?>

 

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 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 may be 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 exception (if there is one).

 

In Example, $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, an error is caught by the catch block for errors.

 

The Error object also includes 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 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();
}
?>

The example 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 user id 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 customer 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('Thesis' , 'Scientist' , '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 preceding statement 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 in row 0 (Thesis). 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 interloop and returns to the top of the inner 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 interloop displays the values in a column within each row. The format used in the preceding 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. 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>";
}

This style is commonly referred to as the $key => $value format. The loop shown in the preceding 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, the $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 Blog, 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";
}
}

 

This code 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 still choose to 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 as follows:
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 blog 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)
{
$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;
}
}
}

 

This loop 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

delete-array

Example  deletesubscript.php

declare(strict_types=1);
function delete_array_value(int $subscript)
{
$customer_record = array (
array('Thesis' ,'Scientist' ,'123 Main Street' ,'Atlanta','GA', 30001), array('Sally' ,'Parisi' ,'101 South Street' ,'Atlanta' , 'GA' , 30001) );
unset($customer_record[$subscript]);
}
delete_array_value(1);

 

The example previously demonstrated the removal of a subscript within a one-dimensional 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 deletesubscript2dim.php

 declare(strict_types=1);
function delete_array_value(int $first_subscript, int $second_subscript)
{
$customer_record = array (
array('Thesis' ,'Scientist' ,'123 Main Street' ,'Atlanta','GA', 30001), array('Sally' ,'Parisi' ,'101 South Street' ,'Atlanta' , 'GA' , 30001)
)
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 of updating values in arrays. Let’s look at another.

declare(strict_types=1);
function update_array_value(int $subscript, $value)
{
$customer_record = array (
array('Thesis' ,'Scientist' ,'123 Main Street' ,'Atlanta','GA', 30001), array('Sally' ,'Parisi' ,'101 South Street' ,'Atlanta' , 'GA' , 30001) );
$customer_record[$subscript] = $value;
}
$temp_array = array('Thesis_r' ,'Scientist' , '1234 Main Street' ,'Atlanta', 'GA', 30001); update_array_value(0, $temp_array);

 

This example totally replaces the Thesis array with a Thesis_r array. 0 is passed into $subscript and the Thesis_r array is passed into $value when the method is called.

 

The method then replaces the contents of position 0 with the values in the Thesis_r array. Actually, it will also insert the array if the position does not currently exist in the array.

If we just want to change one value in the array, we can make a slight adjustment.
declare(strict_types=1);
function update_array_value(int $first_subscript, int $second_subscript, $value)
{
$customer_record = array (
array('Thesis' ,'Scientist' ,'123 Main Street' ,'Atlanta','GA', 30001), array('Sally' ,'Parisi' ,'101 South Street' ,'Atlanta' , 'GA' , 30001) );
$customer_record[$first_subscript][$second_subscript] = $value;
}
update_array_value(0, 0, "Thesis_r");

 

This example would replace Thesis with Thesis_r. 0 is passed into $first_subscript. 0 is also passed into

$second_subscript. Thesis_r is passed into $value when the method is called. The update method then replaces the contents of position 0,0 with Thesis_r. Again, if the position does not exist, it will insert the value into the position.

 

Let’s make a slight change to the example which combined the ability to insert and update. If we are using an array with a 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.

 

Example update_insert_twodim.php

declare(strict_types=1);
function update_array_value( $value, int $first_subscript = -1, int $second_subscript = -1) {
$customer_record = array (
array('Thesis' ,'Scientist' ,'123 Main Street' , 'Atlanta','GA', 30001), array('Sally' ,'Parisi' ,'101 South Street' , 'Atlanta' , 'GA' , 30001) );
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' ,'Scientist' , '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 programming 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.

 

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.

 

Associative and Object Arrays

Object Arrays

So far all the examples have included arrays that use numeric subscripts. They are not very descriptive.

For example:

print customer_record[5];

 

If we ran across this statement in the 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 blog!!

 

What?

All arrays are Associative Arrays. The only difference between what we discussed before and now is what is placed in the subscript.

 

Example process_customer_record.php

><?php // This program 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]."; 
print " You live at $customer_record[2], $customer_record[3],"; print "$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

<?php // This program 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']. "; print "You live at $customer_record['address'], $customer_record['city'],"; 
print "$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 embed 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  process_customer_array_twodim_saved.php <?php
 style="margin:0;height:113px;width:973px">$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, 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

 style="margin:0;width:970px;height:95px">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 last 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 are 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 preceding 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.  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 blog, to return an associative array (MYSQLI_ASSOC).

 

$query .= $customer_info[first_name'] . "," . $customer_info['last_name'] . ","; $query .= $customer_info['address'] . "," . $customer_info['city'] . ","; $query .= $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('Thesis' , 'Scientist' , '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.

$query .= $customer_info[first_name'] . "," .$customer_info['last_name'] . ","; $query .= $customer_info['address'] . "," . $customer_info['city'] . "," ; $query .= $customer_info['state'] ;

$query . = "," . $customer_info['zip_code'] . ")";

 

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' => 'Thesis' , 'last_name' => 'Scientist' , '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] => Thesis [last_name] => Scientist [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 arrayThe key is the subscript name (‘first_name’). The value is the information placed in the location (‘Thesis’).

'first_name' => 'Thesis'
'last_name' => 'Scientist'
'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'];
Scientist

 

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 name for our rows if needed.

$customer_record = array (
'first_customer' =>
array( 'first_name' => 'Thesis' , 'last_name' => 'Scientist' , '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] => Thesis
[last_name] => Scientist [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).

 

Example.  foreachassociative.php

 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: Thesis
Row: first_customer Column: last_name Value: Scientist
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?

why array

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 the Previous Section.

Example deletesubscript2dim.php

declare(strict_types=1);
function delete_array_value(int $first_subscript, string $second_subscript) {
$customer_record = array (
array( 'first_name' =>'Thesis' ,'last_name' =>'Scientist' , '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
)
);
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 an array.

 

Updating & Inserting

array-update

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

 

Example update-associative.php

declare(strict_types=1);
function update_array_value(int $subscript, $value)
{
$customer_record = array (
array('first_name' =>'Thesis' ,'last_name' =>'Scientist', '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)
);
$customer_record[$subscript] = $value;
}
$temp_array =
array('first_name' =>'Thesis' ,'last_name' =>'Scientist' , '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 Thesis array with a Thesis_r array. 0 is still passed into $subscript because no name was provided for the arrays that hold records.

 

Example update_associative2.php

declare(strict_types=1);
function update_array_value(string $subscript, $value)
{
$customer_record = array (
'first_customer' =>
array( 'first_name' => 'Thesis' , 'last_name' => 'Scientist' , '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
)
);
$customer_record[$subscript] = $value;
}
$temp_array =
array( 'first_name' =>'Thesis' ,'last_name' =>'Scientist' , '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 is needed. The data type for the subscript either needs to be changed to string or to be 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 Thesis with the array containing Thesis_r. Actually, it will also insert the array if the position does not currently exist in the array.

 

Let’s take a look at replacing one value. Example.  update_associative3.php

declare(strict_types=1);
function update_array_value(int $first_subscript, string $second_subscript, $value)
{
$customer_record = array (
array( 'first_name' =>'Thesis' ,'last_name' =>'Scientist' , '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
)
);
$customer_record[$first_subscript][$second_subscript] = $value;
}
update_array_value(0, ‘first_name’, "Thesis_r");

 

The data type of the second subscript is changed to a string and the string subscript (first_name) is passed into the method. As we have seen before, this example would replace Thesis with Thesis_r.

 

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.

 

Example.  update_associative4.php

declare(strict_types=1);
function update_array_value(string $first_subscript, string $second_subscript, $value) {
$customer_record = array (
'first_customer' =>
array( 'first_name' => 'Thesis' , 'last_name' => 'Scientist' , '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
)
);
$customer_record[$first_subscript][$second_subscript] = $value;
}
update_array_value(‘first_customer’,'first_name', "Thesis");

 

Let’s revisit the method that combines these ideas.

If we are using an array with a 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.

 

Example insert_update_associative.php

declare(strict_types=1);
function update_array_value( $value, string $first_subscript = "none", string $second_subscript = "none")
{
$customer_record = array (
array('Thesis' ,'Scientist' ,'123 Main Street' , 'Atlanta','GA', 30001), array('Sally' ,'Parisi' ,'101 South Street' , 'Atlanta' , 'GA' , 30001) );
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' ,'Scientist' , '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);

 

As 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 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

Object Arrays

Let’s take a brief look at an Object Array. If you are not familiar with Object-Oriented Programming

<?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 allows 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 declare statement 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 complete 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.

 

Example objectarrays.php

class Customer
{
private $first_name = "NFN";
private $last_name = "NLN";
private $address = "NA";
private $city = "NC";
private $state = "NS";
private $zip_code = "NZC";
function __construct( $value1,
$value2, $value3, $value4,
$value5, $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);
}
function set_first_name( $value)
{
if((strlen($value) > 0) && (strlen($value) < 16))
{
$this->first_name = $value;
}
else
{
throw new Exception("Invalid First Name");
}
}
function set_last_name( $value)
{
if((strlen($value) > 0) && (strlen($value) < 21))
{
$this->last_name = $value;
}
else
{
throw new Exception("Invalid Last Name");
}
}
function set_address( $value)
{
if((strlen($value) > 0) && (strlen($value) < 31))
{
$this->address = $value;
}
else
{
throw new Exception("Invalid Address");
}
}
function set_city( $value)
{
if((strlen($value) > 0) && (strlen($value) < 21))
{
$this->city = $value;
}
else
{
throw new Exception("Invalid City");
}
}
function set_state( $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()
{ return $this->first_name; }
function get_last_name()
{ return $this->last_name; }
function get_address()
{ return $this->address; }
function get_city()
{ return $this->city; }
function get_state()
{ return $this->state; }
function get_zip_code()
{ return $this->zip_code; }
}

 

The preceding class provides a basic structure for storing the customer information. function __construct(string $value1, string $value2, string $value3, string $value4, string $value5, int $value6)

 

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 one customer with just one line of code.

$customer_record[] = new Customer("Thesis", "Scientist",
"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 Thesis.
print $customer_record[0]->get_first_name();
Thesis

 

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

$customer_record[0]->set_first_name('Thesis').

 

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 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) "Steve" ["last_name":"Customer":private]=> string(5) "Scientist" ["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 (“Steve”) and last_name (“Scientist”).

 

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. All things 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 needed 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 the first name.

 

PHP Functions—Changing, Splitting, Slicing, and Sorting Arrays

PHP Functions

In this blog, we will take a brief look at the PHP functions that are available to change, split, slice, and sort arrays. Many of these functions work with multiple array types (single, multidimensional, and/or associative).

 

All descriptions of the following functions are provided by the online PHP manual available at www.php.net. Brief examples using each function and a description of the results of these examples are provided.

 

These examples are only meant to get your feet wet. For a more detailed description of the functions shown, and for more examples, visit the online PHP manual.

 

Changing Array Contents

array_change_key_case

changes the key to uppercase or lowercase “Returns an array with its keys lower or uppercased, or FALSE if the array is not an array.”

 

Syntax: array array_change_key_case ( array $array [, int $case = CASE_LOWER ] )

Example:

$test_array = array('firstname' => 'Jeff', 'lastname' => 'Scientist'); print_r(array_change_key_case($test_array, CASE_UPPER));
Output:
Array
(
[FIRSTNAME] => Jeff
[LASTNAME] => Scientist
)
In this example, the keys (FIRSTNAME, LASTNAME) are uppercased.

 

array_fill

fill an array with values Fills an array with num entries of the value of the value parameter, keys starting at the start_index parameter.

Syntax: array array_fill ( int $start_index , int $num , mixed $value )

The first parameter is the starting index. The second parameter is the ending index.

Example:

$default_array = array_fill(1, 8, 'default');
print_r($default_array);
array_fill_keys
fills an array with values, specifying keys
“Fills an array with the value of the value parameter, using the values of the keys array as keys.”
Syntax:
array array_fill_keys ( array $keys , mixed $value )
Example:
$keys = array('first_name', 'last_name', 'address', 'city', 'state', 'zip'); $default_array = array_fill_keys($keys, 'default'); print_r($default_array);
Output:
Array (
[first_name] => default
[last_name] => default
[address] => default
[city] => default
[state] => default
[zip] => default
)

In this example, the $keys array is used to supply the key. The word ‘default’ is used to fill each position.

 

array_filter

array_filter

filters elements of an array using a callback function Iterates over each value in the array passing them to the callback function. If the callback function returns true, the current value from the array is returned into the result array.

 

Array keys are preserved.” This function can be used in several ways to filter out content you don’t want in your array. You can create a function to filter out unwanted data types that exist in the array or use existing PHP functions.

 

Syntax: array array_filter ( array $array [, callable $callback [, int $flag = 0 ]] )

Example:

$first_array = array('first_name' => 'Thesis' , 'last_name' => 'Scientist' , 'address' => '123 Main Street' , 'city' => 'Atlanta', 'state' => 'GA', 'zip' => 30001);
function filter_array($unfiltered_value)
{
if(is_string($unfiltered_value))
{
return $unfiltered_value;
}
}
print_r(array_filter($first_array, "filter_array"));
Output:
Array (
[first_name] => Thesis
[last_name] => Scientist
[address] => 123 Main Street
[city] => Atlanta
[state] => GA
)

This example would filter out anything that is not a string. Without a function, it will filter out empty strings, NULL, or FALSE.

Example:

$first_array = array('first_name' => '' , 'last_name' => NULL , 'address' => FALSE , 'city' => 'Atlanta', 'state' => 'GA', 'zip' => 30001);
print_r(array_filter($first_array));
Output:
Array (
[city] => Atlanta
[state] => GA
[zip] => 30001
)

 

A PHP compare function can be used instead of a user-defined function. These could include strcmp, strcasecmp, strncasecmp, substrcomp, or other PHP comparison functions that return < 0, 0, or > 0 as a result.

array_flip

exchanges all keys with their associated values in an array “array_flip() returns an array in flip order, i.e. keys from array become values and values from array become keys.”

Syntax: array array_flip ( array $array )

Example:

$first_array = array('first_name' => 'Thesis' , 'last_name' => 'Scientist' , 'address' => '123 Main Street' , 'city' => 'Atlanta', 'state' => 'GA', 'zip_code' => 30001);
$result = array_flip($first_array);
print_r($result);
Output:
Array (
[Thesis] => first_name
[Scientist] => last_name
[123 Main Street] => address
[Atlanta] => city
[GA] => state
[30001] => zip_code
)

In this example, the keys and values in the array $first_array are reversed.

 

array_pad

array_pad

pads an array to the specified length with a value

“array_pad() returns a copy of the array padded to the size specified by size with value. If size is positive then the array is padded on the right, if it's negative then on the left.”

Syntax: array array_pad ( array $array , int $size , mixed $value )

Example:

$first_array = array('Thesis' , 'Scientist' , '123 Main Street' , 'Atlanta', 'GA', '30001');
$second_array = array('Sally' , 'Parisi' , '101 South Street' , 'Atlanta' ,'GA' , '30001');
$first_array = array_pad($first_array, 8, "No Value");
$second_array = array_pad($second_array, -8, "No Value");
print_r($first_array);
print_r($second_array);

 

first_array now has two additional elements at the end of the array. The length of the original array was 6.

The padding size entered was 8. Thus, two extra positions are created.

Second_array now has two additional elements at the front of the array. The padding size entered was –8.

 

array_pop

pops the element off the end of the array

“array_pop() pops and returns the last value of the array, shortening the array by one element.”

 

Syntax: mixed array_pop ( array &$array )

Example:

$first_array = array('Thesis' , 'Scientist' ,'123 Main Street' , 'Atlanta', 'GA', '30001');

print array_pop($first_array);

print_r($first_array);

The last element of $first_array is pulled from the array and displayed via the print statement. The array size is now one less than originally.

 

array_push

array_push

pushes one or more elements onto the end of the array “array_push() treats an array as a stack and pushes the passed variables onto the end of the array. The length of array increases by the number of variables pushed.”

Syntax: int array_push ( array &$array , mixed $value1 [, mixed $... ] )

Example:

$customer_recrod = array (

array('Thesis' , 'Scientist' , '123 Main Street' ,'Atlanta', 'GA', 30001), array('Sally' , 'Parisi' , '101 South Street' ,'Atlanta' , 'GA' , 30001) );

$customer_info = array('Be' , 'Happy' ,'111 North Street' , 'Atlanta' , 'GA' , 30001); array_push($customer_record, $customer_info); print_r($customer_record);

 

array_push adds the Be Happy array to the end of the existing array.

 

array_shift

shifts an element of the beginning of an array

“array_shift() shifts the first value of the array off and returns it, shortening the array by one element and moving everything down. All numerical array keys will be modified to start counting from zero while literal keys won't be touched.”

Syntax: mixed array_shift ( array &$array )

Example:

$first_array = array('first_name' => 'Thesis' ,
'last_name' => 'Scientist' ,
'address' => '123 Main Street' ,
'city' => 'Atlanta', 'state' => 'GA',
'zip_code' => 30001);
$second_array = array('Sally' , 'Parisi' ,'101 South Street' , 'Atlanta' , 'GA' , 30001);
array_shift($first_array);
array_shift($second_array);
print_r($first_array);
print_r($second_array);

In $first_array, first_name has been removed from the front of the array. In $second_array, Sally has been removed and the indexes have been renumbered beginning at 0.

 

array_unshift

array_unshift

prepends one or more elements to the beginning of an array

array_unshift() prepends passed elements to the front of the array. Note that the list of elements is prepended as a whole so that the prepended elements stay in the same order. All numerical array keys will be modified to start counting from zero while literal keys won't be touched. “

 

Syntax: int array_unshift ( array &$array , mixed $value1 [, mixed $... ] )

Example:

$first_array = array('Thesis' ,'Scientist','123 Main Street' ,'Atlanta', 'CA', 30001); 
print(array_unshift($first_array, "770-777-7777", "adm@no.co")); print_r($first_array)

array_unshift will append items to the end of the array. 
The function will return the new size of the array. In this example, two items are added to the end of $first_array.

 

compact

creates an array containing variables and their values “For each of these, compact() looks for a variable with that name in the current symbol table and adds it to the output array such that the variable name becomes the key and the contents of the variable become the value for that key.

 

In short, it does the opposite of extract(). Any strings that are not set will simply be skipped.”

Syntax: array compact ( mixed $varname1 [, mixed $... ] )

Example:

$first_name = "Thesis";
$last_name = "Scientist";
$address = "123 Main Street";
$city = "Atlanta";
$state = "GA";
$zip_code = 30001;
$keys = array("first_name", "last_name",
"address", "city", "state", "zip_code");
$first_array = compact($keys);
print_r($first_array);

 

compact will build an array from existing variable names that are passed. It will use the variable names for the keys creating an associative array. In this example, an array of the variable names is passed, which pulls the values in the variables and creates the array shown. If the variable does not exist, it will ignore it.

 

range

range

creates an array containing a range of elements

Syntax: array range ( mixed $start , mixed $end [, number $step = 1 ] )

Example:

print_r(range(1,10));

range provides a quick way to generate sequential values for an array.

Example: print_r(range('A','F'));

 

Splitting and Slicing Arrays

Splitting and Slicing Arrays

array_chunk

splits an array into chunks “Chunks an array into arrays with size elements. The last chunk may contain less than size elements.”

Syntax: array array_chunk ( array $array , int $size [, bool $preserve_keys = false ] )

Example:

$test_array = array('Jeff', 'Scientist', '123 Main Street', 'Atlanta', 'GA', '30001'); print_r(array_chunk($test_array, 2));

In this example, the original keys (subscripts) are retained within the new two-dimensional array.

 

array_slice

extracts a slice of the array “array_slice() returns the sequence of elements from the array as specified by the offset and length parameters.”

 

Syntax: array array_slice ( array $array , int $offset [, int $length = NULL [, bool $preserve_keys = false ]] )

Example:

$second_array = array('Sally' , 'Parisi' ,

'101 South Street' , 'Atlanta' , 'GA' , 30001);

print_r(array_slice($second_array, 2)); print_r(array_slice($second_array, -2, 1)); print_r(array_slice($second_array, 0, 2)); print_r(array_slice($second_array, 2, -1)); print_r(array_slice($second_array, 2, -1, true));

Passing just a 2 will return all values starting at position 2 (101 South Street, Atlanta, 30001).

Passing a –2 and 1 will slice from the right instead of left, starting at the second to last right position and return one value (GA).

Passing a 0 and 2 will start at position 0 and return two values (Sally, Parisi).

Passing a 2 and –1 will start at position 2 and return all items up to the second-to-last right-most item

(101 South Street, Atlanta).

Passing 2, –1, and TRUE will return the same as the previous example, except the original indexes are retained.

 

array_splice

removes a portion of the array and replace it with something else “Removes the elements designated by offset and length from the input array, and replaces them with the elements of the replacement array, if supplied.”

 

Syntax: array array_splice ( array &$input , int $offset [, int $length = 0 [, mixed $replacement = array() ]] )

Example:

$second_array = array('Sally' , 'Parisi' , '101 South Street' , 'Atlanta' , 'GA' , 30001);

print_r(array_splice($second_array, 2));

print_r(array_splice($second_array, 0, 1));

In the first example, 2 is passed, which requests that the contents of the array $second_array are retained starting at index 2 (the address). In the second example, 0 and 1 are passed, indicating that starting at position 0, one item should be retained (the first name).

 

Sorting Arrays

Sorting Arrays

array_multisort

sorts multiple or multidimensional arrays “array_multisort() can be used to sort several arrays at once, or a multidimensional array by one or more dimensions. Associative (string) keys will be maintained, but numeric keys will be reindexed.

 

Sorting type flags:

  •  SORT_REGULAR - compare items normally (don't change types)
  • SORT_NUMERIC - compare items numerically
  • SORT_STRING - compare items as strings
  • SORT_LOCALE_STRING - compare items as strings, based on the current locale. It uses the locale, which can be changed using setlocale()
  • SORT_NATURAL - compare items as strings using "natural ordering" like natsort()
  • SORT_FLAG_CASE - can be combined (bitwise OR) with SORT_STRING or SORT_NATURAL to sort strings case-insensitively”

 

Syntax:

bool array_multisort ( array &$array1 [, mixed $array1_sort_order = SORT_ASC [, mixed $array1_sort_flags = SORT_REGULAR [, mixed $... ]]] )

Example:

$first_array = array('Thesis' , 'Scientist' ,'123 Main Street' , 'Atlanta', 'GA', '30001');

$second_array = array('Sally' , 'Parisi' , '101 South Street' , 'Atlanta' ,'GA' , '30001');

array_multisort($first_array, SORT_ASC,

$second_array, SORT_DESC );

print_r($first_array);

print_r($second_array);

In this example,

$first_array values are sorted as strings in ascending order. String numbers (123, 30001) are first in sorting order followed by ‘A’, ‘G’, ‘P’, and ‘S’.

$second_array values are sorted as strings in descending order. String numbers (123, 30001) are first in sorting order followed by ‘A’, ‘G’, ‘S’, and ‘P’.

 

array_reverse

returns an array with elements in reverse order “Takes an input array and returns a new array with the order of the elements reversed.”

Syntax: array array_reverse ( array $array [, bool $preserve_keys = false ] )

Example:

$first_array = array('first_name' => 'Thesis' ,
'last_name' => 'Scientist' , 'address' => '123 Main Street' , 'city' => 'Atlanta', 'state' =>'GA', 'zip_code' => 30001);
first_array = array('first_name' => 'Thesis' ,
'last_name' => 'Scientist' , 'address' => '123 Main Street' ,
'city' => 'Atlanta', 'state' =>'GA', 'zip_code' => 30001);
print_r(array_reverse($first_array));
print_r(array_reverse($second_array));
print_r(array_reverse($second_array, TRUE));

 

In this example, the elements in $first_array are returned in reverse order. $second_array is also returned in reverse order.

When passing TRUE in the second parameter, the original numerical indexes are retained.

 

arsort

arsort

sorts an array in reverse order and maintains index associationThis function sorts an array such that array indices maintain their correlation with the array elements they are associated with. This is used mainly when sorting associative arrays where the actual element order is significant.”

 

Syntax: bool arsort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

Example:

$first_array = array('first_name' => 'Thesis' , 'last_name' => 'Scientist' ,
'address' => '123 Main Street' , 'city' => 'Atlanta', 'state' => 'CA', 'zip_code' => 30001);
arsort($first_array);
print_r($first_array);
Output:
Array (
[zip_code] => 30001
[last_name] => Scientist
[first_name] => Thesis
[state] => CA
[city] => Atlanta
[address] => 123 Main Street
)

arsort is used with associative arrays to sort values. It sorts values in reverse alphabetical order. In this example, the ZIP code is listed first because it is numeric. The remaining values are in reverse order. The keys (subscripts) are maintained.

 

asort

sorts an array and maintain index association “This function sorts an array such that array indices maintain their correlation with the array elements they are associated with. This is used mainly when sorting associative arrays where the actual element order is significant.”

 

Syntax: bool asort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

Example:

$first_array = array('first_name' => 'Thesis' ,
'last_name' => 'Scientist' ,
'address' => '123 Main Street' ,
'city' => 'Atlanta',
'state' => 'CA', 'zip_code' => 30001);
asort($first_array);
print_r($first_array);
Output:
Array (
[address] => 123 Main Street
[city] => Atlanta
[state] => CA
[first_name] => Thesis
[last_name] => Scientist
[zip_code] => 30001
)

The function asort is used with associative arrays to sort values. It sorts values in alphabetic order. In this example, the ZIP code is listed last because it is numeric. The remaining values are in alphabetic order. The keys (subscripts) are maintained.

 

krsort

krsort

sorts an array by key in reverse order “Sorts an array by key in reverse order, maintaining a key to data correlations. This is useful mainly for associative arrays.”

 

Syntax: bool krsort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

Example:

$first_array = array('first_name' => 'Thesis' , 'last_name' => 'Scientist' , 'address' => '123 Main Street' , 'city' => 'Atlanta', 'state' => 'CA', 'zip_code' => 30001);
krsort($first_array);
print_r($first_array);
Output:
Array (
[zip_code] => 30001
[state] => CA
[last_name] => Scientist
[first_name] => Thesis
[city] => Atlanta
[address] => 123 Main Street
)

krsort sorts keys in reverse alphabetic order. In this example, zip_code is now first in the array, and address is last.

 

ksort: sorts an array by key “Sorts an array by key, maintaining a key to data correlations. This is useful mainly for associative arrays.”

Syntax: bool ksort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

Example:

$first_array = array('first_name' => 'Thesis' ,
'last_name' => 'Scientist' ,
'address' => '123 Main Street',
'city' => 'Atlanta', 'state' => 'CA',
'zip_code' => 30001);
ksort($first_array);
print_r($first_array);
Output:
Array (
[address] => 123 Main Street
[city] => Atlanta
[first_name] => Thesis
[last_name] => Scientist
[state] => CA
[zip_code] => 30001
)

ksort sorts array kesy in alphabetic order. In this example, the address is now first in the array, and zip_code is last.

 

natcasesort

natcasesort

sorts an array using a case insensitive "natural order" algorithm This function implements a sort algorithm that orders alphanumeric strings in the way a human being would while maintaining key/value associations. This is described as a "natural ordering".”

Syntax: bool natcasesort ( array &$array )

Example:

$name_array =

array("Thesis", "Thesis_r", "jones", "Jones");

natcasesort($name_array);

print_r($name_array);

 

natcasesort arranges items in a way that is more natural to humans. In this example, all the Jones values appear before any of the Thesis values. It ignores case.

 

natsort

sorts an array using a "natural order" algorithm “This function implements a sort algorithm that orders alphanumeric strings in the way a human being would while maintaining key/value associations. This is described as a "natural ordering".”

Syntax: bool natsort ( array &$array )

Example:

$name_array = array("Thesis", "Thesis_r",

"jones", "Jones");

natsort($name_array);

print_r($name_array);

 

natsort sorts in a human natural way. However, it does not ignore the case. In the preceding example, all uppercase words occur before lowercase. However, notice that the keys (subscripts) are retained, unlike sort.

 

rsort: sorts an array in reverse order “This function sorts an array in reverse order (highest to lowest).”

Syntax: bool rsort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

Example:

$first_array = array('first_name' => 'Thesis' ,

'last_name' => 'Scientist' , 'address' => '123 Main Street' , 'city' => 'Atlanta', 'state' => 'CA', 'zip_code' => 30001);

rsort($first_array);

print_r($first_array);

 

rsort sorts the values in an array in reverse alphabetic order. It does not maintain the keys (subscripts) from the original array. As seen from the example, numerical values would exist first in the sorted array.

 

shuffle

shuffle-array

shuffles an array “This function shuffles (randomizes the order of the elements in) an array.”

Syntax: bool shuffle ( array &$array )

 

Example:

$first_array = array('first_name' => 'Thesis' ,

'last_name' => 'Scientist' , 'address' => '123 Main Street' , 'city' => 'Atlanta', 'state' => 'CA', 'zip_code' => 30001);

shuffle($first_array);

print_r($first_array);

shuffle randomly sorts the order of the values in an array. It does not maintain the keys (subscripts).

 

sort: sorts an array “This function sorts an array. Elements will be arranged from lowest to highest when this function has completed.”

Syntax: bool sort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

Example:

$first_array = array('first_name' => 'Thesis' ,
'last_name' => 'Scientist' , 'address' => '123 Main Street' ,
'city' => 'Atlanta', 'state' => 'CA', 'zip_code' => 30001);
sort($first_array);
print_r($first_array);

sort shuffles the array into alphabetic order; it does not maintain the keys (subscripts). String values naturally occur first in the sort order before numerical values as shown in the example.

 

uasort

uasort

sorts an array with a user-defined comparison function and maintain index association

“This function sorts an array such that array indices maintain their correlation with the array elements they are associated with, using a user-defined comparison function. This is used mainly when sorting associative arrays where the actual element order is significant.”

Syntax: bool uasort ( array &$array , callable $value_compare_func )

Example:

function value_compare($first_value, $second_value)
{
if ($first_value == $second_value)
return 0;
else if ($first_value > $second_value)
return 1;
else
return -1;
}
$first_array = array('first_name' => 'Thesis' ,
'last_name' => 'Scientist' , 'address' => '123 Main Street' ,
'city' => 'Atlanta', 'state' => 'CA', 'zip_code' => 30001);
uasort($first_array, 'value_compare');
print_r($first_array);
Output:
Array (
[address] => 123 Main Street
[city] => Atlanta
[state] => CA
[first_name] => Thesis
[last_name] => Scientist
[zip_code] => 30001
)

uasort sorts the array in ascending order of the values in each element as determined by a user-supplied function which evaluates what is equal, greater than, or less than. The keys (subscripts) are maintained from the original array.

 

The user can modify the comparison shown (such as using === instead of ==) to determine what is “equal..” The user-supplied function must return a value < 0, 0, and > 0, as shown in the example function.

uasort($first_array, "strcmp”);

print_r($first_array);

A PHP compare function can be used instead of a user-defined function. These could include strcmp, strcasecmp, strncasecmp, substrcomp, or other PHP comparison functions that return < 0, 0, or > 0 as a result.

 

uksort

sorts an array by keys using a user-defined comparison function “uksort() will sort the keys of an array using a user-supplied comparison function. If the array you wish to sort needs to be sorted by some non-trivial criteria, you should use this function.”

Syntax: bool uksort ( array &$array , callable $key_compare_func )

Example:

function key_compare($first_key, $second_key)
{
if ($first_key == $second_key)
return 0;
else if ($first_key > $second_key)
return 1;
else
return -1;
}
uksort($first_array, "key_compare");
print_r($first_array);
Output:
Array (
[address] => 123 Main Street
[city] => Atlanta
[first_name] => Thesis
[last_name] => Scientist
[state] => CA
[zip_code] => 30001
)

uksort sorts an array in ascending order by keys (subscripts) based on the comparison provided by a user-supplied function. The function must determine what is equal, what is greater than, and what is less than. The keys (subscripts) from the original array are maintained.

 

The user can modify the comparison shown (such as using === instead of ==) to determine what is “equal.” The user-supplied function must return a value < 0, 0, and > 0, as shown in the example function.

uksort($first_array, "strcmp”);

print_r($first_array);

A PHP compare function can be used instead of a user-defined function. These could include strcmp, strcasecmp, strncasecmp, substrcomp, or other PHP comparison functions that return < 0, 0, or > 0 as a result.

 

usort

sorts an array by values using a user-defined comparison function “This function will sort an array by its values using a user-supplied comparison function. If the array you wish to sort needs to be sorted by some non-trivial criteria, you should use this function.”

Syntax: bool usort ( array &$array , callable $value_compare_func )

 

Example:

function value_compare($first_value,
$second_value)
{
if ($first_value == $second_value)
return 0;
else if ($first_value > $second_value)
return 1;
else
return -1;
}
$first_array = array('first_name' => 'Thesis' ,
'last_name' => 'Scientist' , 'address' => '123 Main Street' ,
'city' => 'Atlanta', 'state' => 'CA', 'zip_code' => 30001);
usort($first_array, 'value_compare');
print_r($first_array);

usort sorts the array in ascending order of the values in each element as determined by a user-supplied function which evaluates what is equal, greater than, or less than. The keys (subscripts) are not maintained from the original array.

 

The user can modify the comparison shown (such as using === instead of ==) to determine what is “equal.” The user-supplied function must return a value < 0, 0, and > 0, as shown in the example function.

usort($first_array, "strcmp”);

print_r($first_array);

A PHP compare function can be used instead of a user-defined function. These could include strcmp, strcasecmp, strncasecmp, substrcomp, or other PHP comparison functions that return < 0, 0, or > 0 as a result.

 

PHP Property

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 this example, $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

 

Example  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>

The example provides a pretty typical web form that requests information from the user. The HTML showed also filters the information accepted by the user, using HTML 5, to ensure 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.

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

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 preceding example). The values assigned to the properties are retrieved from the information entered by the user in the textboxes.

 

Example  Properties and values sent to process_customer.php

first_name = "Steve"
last_name = "Scientist"
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 website to be a string.

 

Thus, as shown in Example, 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 property at any time.

$zip_code = "30001";

$zip_code = 30001;

 

The first statement in the preceding 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  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."; print "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 URL address in the browser. Information passed via get will display on the URL line.

 

Why Do We Have a Choice?

PHP Arrays

 

Information passed via getting does not use as much server memory because it is contained 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 considered 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 (‘Steve’). 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']);

 

This line 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 preceding example, 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 are 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 fewer 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 the preceding. 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 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.

Recommend