0% found this document useful (0 votes)
13 views

Web-Apps-Chapter-8-PHP Array

The document discusses PHP arrays including indexed, associative, and multidimensional arrays. It covers creating, accessing, adding, deleting, merging, and sorting array elements as well as built-in PHP array functions.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Web-Apps-Chapter-8-PHP Array

The document discusses PHP arrays including indexed, associative, and multidimensional arrays. It covers creating, accessing, adding, deleting, merging, and sorting array elements as well as built-in PHP array functions.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

WEBAPPS

Web Application using PHP and MySQL


Chapter 9: PHP Array
Learning Objectives:
The student will be able to:
• Declare arrays
• Initialize an array
• Differentiate index and associative array
• Add an item to an array
• Delete, merge and sort an array
• Create an HTML Form components using
Array
Topics
✓ Array
❑ Index or Numeric Array
❑ Associative Array
❑ Multidimensional Array
✓ Adding Items to an Array
✓ Deleting Array and Array Elements
✓ Merging and Sorting Array
✓ Array Functions
✓ Transforming between String and Array
✓ Creating an Array from an HTML Form
PHP Array
Arrays in PHP are a type of data structure that allows us to store multiple elements
of similar or different data types under a single variable thereby saving us the effort
of creating a different variable for every data. The arrays are helpful to create a list
of elements of similar types, which can be accessed using their index or key.

Array use keys to create and retrieved the value they store. The resulting structure
– a list of key-value pairs – looks similar to a two-column spreadsheet. Interestingly,
the array structure in PHP is so flexible that it can use either numbers or strings for
both the keys and the values. The array doesn’t even need to be consistent in this
respect.

Suppose we want to store five names and print them accordingly. This can be easily
done by the use of five different string variables. But if instead of five, the number
rises to a hundred, then it would be really difficult for the user or developer to
create so many different variables. Here array comes into play and helps us to store
every element within a single variable and also allows easy access using an index or
a key. An array is created using an array() function in PHP.
Types of Array
• Indexed or Numeric Arrays: An array with a numeric index
where values are stored linearly.
• Associative Arrays: An array with a string index where instead of
linear storage, each value can be assigned a specific key.
• Multidimensional Arrays: An array that contains a single or
multiple arrays within it and can be accessed via multiple
indices.
Index or Numeric Array
These type of arrays can be used to store any type of element, but an index is always a number.
By default, the index starts at zero. These arrays can be created in two different ways.
Example #1:
Output:
Index or Numeric Array
Example 2: We can traverse an indexed array using loops in PHP.
Output:

Traversing: We can loop through the indexed array in two ways. First by using for loop and
secondly by using foreach.
Index or Numeric Array
Example 3: Creating an indexed array using the range() in PHP.
Output:
Associative Array
These types of arrays are similar to the indexed arrays but instead of linear storage, every value
can be assigned with a user-defined key of string type.
Example #1:
Output:
Associative Array
Example 2: We can traverse associative arrays in a similar way did in numeric arrays using loops.
Output:

Traversing: We can loop through the indexed array in two ways. First by using for loop and
secondly by using foreach.
Associative Array
Example 3: Creating an associative array of mixed types.
Output:
Multidimensional Array
Multi-dimensional arrays are such arrays that store another array at each index instead of a single element.
In other words, we can define multi-dimensional arrays as an array of arrays. As the name suggests, every
element in this array can be an array and they can also hold other sub-arrays within. Arrays or sub-arrays in
multidimensional arrays can be accessed using multiple dimensions.
Example #1: Output:
Multidimensional Array
Example 2: We can traverse multidimensional arrays using for and foreach loop in a nested way.
Output:

Traversing Multidimensional Arrays: That is, one for loop for the outer array and one foreach
loop for the inner array.
Multidimensional Array
Example 3: We can traverse multidimensional arrays using foreach loop in a nested way.

Output:

Traversing Multidimensional Arrays: That is, one foreach loop for the outer array and another
foreach loop for the inner array.
Creating an Array of HTML Components
Output:
Adding Item to an Array
n PHP, once an array exists, you can add extra elements to the array with the assignment operator (the equal sign), in a way
similar to how you assign a value to a string or a number. When doing so, you can either specify the key of the added
element or not, but in either case, you must refer to the array with the square brackets.

Example:
$list = array(1=>‘apples’,2=>’bananas’,3=>’oranges’);

To add two items to the $list array, you’d write


$list[]=’pears’;
$list[]=’tomatoes’;

If you don’t specify the key, each element is appended to the exiting array, indexed with the next sequential number.
Assuming this is the same array from the previous section, which was indexed at 1, 2, and 3, pears is now located at 4 and
tomatoes at 5.

If you do specify the index, the value is assigned at that location. Any existing value already indexed at that point are
overwritten, like so:

$list[3]=’pears’;
$list[4]=’tomatoes’;

Now, the value of the elements in the fourth position of the array is tomatoes, and no element of $list is equal to oranges
(this value was overwritten by pears). With this in mind, unless you intend to overwrite any existing data, you’ll better off
not including a specific key when adding values to your arrays. However, if the array uses strings for indices, you’ll probably
want to specify keys so you don’t end up with an odd combination of strings and number keys.
Deleting Array and Array Elements
You won’t need to delete an individual item from an array frequently, but it’s possible
to do so by using the unset() function:
unset($array[4]);
unset($array[‘name']);

This function eliminates a variable and frees up the memory it used. When applied
up to an array element, that element is deleted; if you apply unset() to an entire array
or any other variable type, the whole variable is deleted:

unset($array);
unset($string);

You can also reset an array (empty it without deleting the variable altogether) using
the array() function:

$array = array();

This has the effect of initializing the variable: making it exist and defining its type
without assigning a value.
Merging and Sorting an Array
Merging
PHP has a function that allows you to append one array onto another. Think of it as
concatenation for arrays. The function, array_merge(), works like so:
$new_array = array_merge($array1,$array2);

Sorting
PHP supports a variety of ways to sort an array. Sort refers to an alphabetical sort if
the values being sorted are strings or numerical sort if the values being sort are
numbers. When you’re sorting an array, you must keep in mind that an array consists
of pairs of keys and values. Thus, an array can be sorted based on the keys or the
values. This is further complicated by the fact that you can sort the values and keep
the corresponding keys aligned or you can sort the values and have them be assigned
new keys.
PHP Array functions
PHP Arrays are a data structure that stores multiple elements of a
similar type in a single variable. The arrays are helpful to create a
list of elements of similar type. It can be accessed using their index
number or key. The array functions are allowed to interact and
manipulate the array elements in various ways. The PHP array
functions are used for single and multi-dimensional arrays.

• The array() function is used to create an array.


• The range() function creates an array containing a range of
elements.
– This function returns an array of elements from low to high.
– Note: If the low parameter is higher than the high parameter, the
range array will be from high to low.
PHP Array functions
• The array_keys() function returns an array containing the keys.
• The count() function returns the number of elements in an array.
• The array_count_values() function counts all the values of an array.
• The array_rand() function returns a random key from an array, or it
returns an array of random keys if you specify that the function
should return more than one key.
• The array_merge() function merges one or more arrays into one
array.
– Tip: You can assign one array to the function, or as many as you like.
– Note: If two or more array elements have the same key, the last one
overrides the others.
– Note: If you assign only one array to the array_merge() function, and the
keys are integers, the function returns a new array with integer keys
starting at 0 and increases by 1 for each value (See example below).
PHP Array functions
• The array_search() function search an array for a value and returns
the key.
• The array_values() function returns an array containing all the
values of an array.
– Tip: The returned array will have numeric keys, starting at 0 and increase
by 1.
• The in_array() function searches an array for a specific value.
– Note: If the search parameter is a string and the type parameter is set to
TRUE, the search is case-sensitive.
• The list() function is used to assign values to a list of variables in
one operation.
• The array_count_values() function counts all the values of an array.
– Note: array_count_values() returns an associative array, where the keys
are the original array's values, and the values are the number of
occurrences
• The unset() function unsets a variable.
PHP Sorting Array functions
• The sort() function sorts an indexed array in ascending order.
• The rsort() function sorts an indexed array in descending order.
• The asort() function sorts an associative array in ascending order,
according to the value.
• The arsort() function sorts an associative array in descending order,
according to the value.
• The ksort() function sorts an associative array in ascending order,
according to the key.
• The krsort() function sorts an associative array in descending order,
according to the key.
• The shuffle() function randomizes the order of the elements in the
array.
– This function assigns new keys for the elements in the array. Existing keys
will be removed.
Transforming from Array to String and vice versa
• The implode() function returns a string from the
elements of an array.
– Note: The implode() function accept its parameters in either
order. However, for consistency with explode(), you should
use the documented order of arguments.
– Note: The separator parameter of implode() is optional.
However, it is recommended to always use two parameters
for backwards compatibility.
– Note: This function is binary-safe.
• The explode() function breaks a string into an array.
– Note: The "separator" parameter cannot be an empty string.
– Note: This function is binary-safe.
Seatwork/Activity
Create an HTML form that adds radio buttons for
civil status such Single, Married, Widow, Separated.
Use array in generating the radio buttons.

Your solution should be in two files. Once the submit


button is clicked it will return the selected civil status
on the second file using page redirection.
That ends our WEEK 7 – Topic 6!
NEXT MEETING –
WEEK 8 – TOPIC 7 – PHP ARRAY

You might also like