Comprehensive Guide to PHP Arrays and Array Functions
Fundamentals of PHP Arrays
Definition and Core Concept:
An array is a specialized variable capable of storing more than one value simultaneously under a single variable name.
Without arrays, storing multiple related items requires declaring separate individual variables:
php $courses1="BSIT"; $courses2="BSHRM"; $courses3="ACT"; Individual variable declarations become unmanageable when scaling up data sets (for instance, managing or more courses instead of ) or when attempting to iterate through a list to locate a specific element.
Arrays solve this scalability issue by consolidating multiple values under a shared identifier, allowing individual elements to be accessed via numeric index numbers or named keys.
PHP Architecture and Features:
Arrays and their manipulation functions are integral components of the PHP core, requiring no additional installation or extension packages.
Core architectural benefits associated with PHP in data processing include:
SEO Friendly: Facilitates clean routing and URL structuring.
Flexible: Dynamically accommodates varying data structures and mixed data types.
Saves Cost: Open-source runtime environment eliminating licensing fees.
Multiple Database Support: Interfaces seamlessly with diverse database engines.
Saves Time: Extensive library of built-in array handling functions speeds development.
Easy to Comprehend: Straightforward syntax for declaration and manipulation.
Array Creation Syntax:
Arrays in PHP are initialized using the built-in language construct or function
array():php array();
Three Primary Array Classifications:
Indexed Arrays: Arrays accessed via numeric indices.
Associative Arrays: Arrays accessed via explicit named keys.
Multidimensional Arrays: Arrays that contain one or more nested arrays within their structure.
Indexed Arrays: Declaration, Access, and Iteration
Mechanisms of Index Assignment:
Automatic Assignment: PHP assigns numeric indices automatically starting strictly at index :
php $courses = array("BSIT", "BSHRM", "ACT"); In this structure, index maps to
"BSIT", index maps to"BSHRM", and index maps to"ACT".
Manual Assignment: Indices can be defined explicitly and individually via square bracket notation:
php $cars[0] = "Volvo"; $cars[1] = "BMW"; $cars[2] = "Toyota"; Accessing and Concatenating Elements:
Elements are retrieved by placing their target numeric index within square brackets directly after the array variable name:
php <?php $courses = array("BSIT", "BSHRM", "ACT"); echo "List of courses " . $courses[0] . ", " . $courses[1] . " and " . $courses[2] . "."; ?>
Output generated:
text List of courses BSIT, BSHRM and ACT. Iterating Through Indexed Arrays:
Sequential looping across all values is performed using a
forloop evaluated against the array length determined bycount():php <?php $courses = array("BSIT", "BSHRM", "ACT"); courses); for($x = 0; $x < $arrlength; $x++) { echo x]; echo "<br>"; } ?>
Associative Arrays: Key-Value Mapping and Traversal
Definition and Structure:
Associative arrays replace zero-based numeric indices with descriptive named string keys assigned to each corresponding value.
Creation Approaches:
Inline Initialization with Fat Arrow (
=>):php $age = array("John" => "25", "Fred" => "27", "Max" => "63");
Direct Explicit Assignment:
php $age['John'] = "25"; $age['Fred'] = "27"; $age['Max'] = "63"; Accessing Associative Elements:
Elements are retrieved by supplying the specific key identifier within brackets:
php <?php $age = array("John" => "25", "Fred" => "27", "Max" => "63"); echo "Peter is " . $age['Peter'] . " years old."; ?>
Traversing Associative Arrays with
foreach:Iteration over associative structures is achieved using the
foreachconstruct to extract each key along with its paired value:php <?php age as $x => $x_value) { echo "Key=" . $x . ", Value=" . $x_value; echo "<br>"; } ?>
Multidimensional Arrays
Structural Principles:
A multidimensional array is defined as an array containing one or more arrays nested within it.
PHP supports multidimensional nesting spanning two, three, four, five, or more levels deep.
Practical usability limitation: arrays nested more than levels deep become difficult to manage, trace, and maintain for most developers.
Dimensionality and Selection Indices:
The dimension of an array dictates the exact number of indices required to select and isolate a specific leaf element:
Two-dimensional array: Requires exactly indices to select an element (
$array[row][column]).Three-dimensional array: Requires exactly indices to select an element (
$array[level][row][column]).
Access Example in a Multi-Row Data Set:
Multi-index selection within a two-dimensional record table representing automobile inventory and sales:
php <?php echo $cars[0][0] . ": In stock: " . $cars[0][1] . ", sold: " . $cars[0][2] . ".<br>"; echo $cars[1][0] . ": In stock: " . $cars[1][1] . ", sold: " . $cars[1][2] . ".<br>"; echo $cars[2][0] . ": In stock: " . $cars[2][1] . ", sold: " . $cars[2][2] . ".<br>"; echo $cars[3][0] . ": In stock: " . $cars[3][1] . ", sold: " . $cars[3][2] . ".<br>"; ?>
Master Reference of Core PHP Array Functions
array(): Creates an array.array_change_key_case(): Changes all keys in an array to lowercase or uppercase.array_chunk(): Splits an array into chunks of arrays.array_column(): Returns the values from a single column in the input array.array_combine(): Creates an array by using the elements from one "keys" array and one "values" array.array_count_values(): Counts all the values of an array.array_diff(): Compares arrays and returns the differences (comparing values only).array_diff_assoc(): Compares arrays and returns the differences (comparing both keys and values).array_diff_key(): Compares arrays and returns the differences (comparing keys only).array_diff_uassoc(): Compares arrays and returns the differences (comparing keys and values using a user-defined key comparison function).array_diff_ukey(): Compares arrays and returns the differences (comparing keys only using a user-defined key comparison function).array_fill(): Fills an array with values.array_fill_keys(): Fills an array with values, specifying keys.array_filter(): Filters the values of an array using a callback function.array_flip(): Flips/exchanges all keys with their associated values in an array.array_intersect(): Compares arrays and returns the matches (comparing values only).array_intersect_assoc(): Compares arrays and returns the matches (comparing both keys and values).array_intersect_key(): Compares arrays and returns the matches (comparing keys only).array_intersect_uassoc(): Compares arrays and returns the matches (comparing keys and values using a user-defined key comparison function).array_intersect_ukey(): Compares arrays and returns the matches (comparing keys only using a user-defined key comparison function).array_key_exists(): Checks if the specified key exists in the array.array_keys(): Returns all the keys of an array.array_map(): Sends each value of an array to a user-made function, which returns new values.array_merge(): Merges one or more arrays into one array.array_merge_recursive(): Merges one or more arrays into one array recursively.array_multisort(): Sorts multiple or multi-dimensional arrays.array_pad(): Inserts a specified number of items, with a specified value, into an array.array_pop(): Deletes the last element of an array.array_product(): Calculates the product of the values in an array.array_push(): Inserts one or more elements to the end of an array.array_rand(): Returns one or more random keys from an array.array_reduce(): Returns an array as a string, using a user-defined function.array_replace(): Replaces the values of the first array with the values from following arrays.array_replace_recursive(): Replaces the values of the first array with the values from following arrays recursively.array_reverse(): Returns an array in the reverse order.array_search(): Searches an array for a given value and returns the key.array_shift(): Removes the first element from an array, and returns the value of the removed element.array_slice(): Returns selected parts of an array.array_splice(): Removes and replaces specified elements of an array.array_sum(): Returns the sum of the values in an array.array_udiff(): Compares arrays and returns the differences (comparing values only using a user-defined key comparison function).array_udiff_assoc(): Compares arrays and returns the differences (comparing keys and values using a built-in function to compare the keys and a user-defined function to compare the values).array_udiff_uassoc(): Compares arrays and returns the differences (comparing keys and values using two user-defined key comparison functions).array_uintersect(): Compares arrays and returns the matches (comparing values only using a user-defined key comparison function).array_uintersect_assoc(): Compares arrays and returns the matches (comparing keys and values using a built-in function to compare the keys and a user-defined function to compare the values).array_uintersect_uassoc(): Compares arrays and returns the matches (comparing keys and values using two user-defined key comparison functions).array_unique(): Removes duplicate values from an array.array_unshift(): Adds one or more elements to the beginning of an array.array_values(): Returns all the values of an array.array_walk(): Applies a user function to every member of an array.array_walk_recursive(): Applies a user function recursively to every member of an array.arsort(): Sorts an associative array in descending order, according to the value.asort(): Sorts an associative array in ascending order, according to the value.compact(): Creates an array containing variables and their values.count(): Returns the number of elements in an array.current(): Returns the current element in an array.each(): Deprecated from PHP . Returns the current key and value pair from an array.end(): Sets the internal pointer of an array to its last element.extract(): Imports variables into the current symbol table from an array.in_array(): Checks if a specified value exists in an array.key(): Fetches a key from an array.krsort(): Sorts an associative array in descending order, according to the key.ksort(): Sorts an associative array in ascending order, according to the key.list(): Assigns variables as if they were an array.natcasesort(): Sorts an array using a case-insensitive "natural order" algorithm.natsort(): Sorts an array using a "natural order" algorithm.next(): Advances the internal array pointer of an array.pos(): Alias ofcurrent().prev(): Rewinds the internal array pointer.range(): Creates an array containing a range of elements.reset(): Sets the internal pointer of an array to its first element.rsort(): Sorts an indexed array in descending order.shuffle(): Shuffles an array.sizeof(): Alias ofcount().sort(): Sorts an indexed array in ascending order.uasort(): Sorts an array by values using a user-defined comparison function.uksort(): Sorts an array by keys using a user-defined comparison function.usort(): Sorts an array using a user-defined comparison function.
Detailed Parameter Specifications and Implementations
array_change_key_case():Description: Changes all keys in an array to lowercase or uppercase.
Parameters:
array(Required): Specifies the target array to use.case(Optional): Specifies the case transformation. Acceptable constants:CASE_LOWER: Default setting. Converts all keys to lowercase.CASE_UPPER: Converts all keys to uppercase.
Code Example:
php <?php age, CASE_UPPER)); ?>
array_chunk():Description: Divides an input array into smaller chunks of new arrays.
Parameters:
array(Required): Specifies the array to split.size(Required): An integer specifying the maximum element capacity of each chunk.preserve_key(Optional): Determines whether original keys are preserved:true: Retains original indices and keys.false: Default setting. Re-indexes each generated chunk numerically.
Code Example:
php <?php cars, 2)); ?>
array_column():Description: Extracts and returns the values from a single column across a multi-dimensional array or record set.
Parameters:
array(Required): Specifies the multi-dimensional array (record set). As of PHP , this parameter also accepts an array of objects.column_key(Required): An integer index or string key name representing the column values to return. Can also be passed asNULLto retrieve complete sub-arrays (useful in conjunction withindex_keyfor re-indexing).index_key(Optional): The column to serve as the index/keys for the returned array.Code Example:
php <?php $a = array( array( 'id' => 5698, 'first_name' => 'Peter', 'last_name' => 'Griffin', ), array( 'id' => 4767, 'first_name' => 'Ben', 'last_name' => 'Smith', ) ); $last_names = array_column(last_names); ?>
array_combine():Description: Generates an associative array using one array for keys and a second array for values.
Parameters:
keys(Required): Array containing the keys to apply.values(Required): Array containing the corresponding values.Code Example:
php <?php $fname = array("Peter", "Ben", "Joe"); $age = array("35", "37", "43"); fname, c); ?>
array_count_values():Description: Computes frequency counts for all distinct values present in an array.
Parameters:
array(Required): Specifies the array to evaluate.Code Example:
php <?php a)); ?>
array_diff():Description: Compares values across two or more arrays and returns an array containing values from
a2,$a3, etc.Code Example:
php <?php $a1 = array("a" => "red", "b" => "green", "c" => "blue", "d" => "yellow"); $a2 = array("e" => "red", "f" => "green", "g" => "blue"); $result = array_diff($a1, $a2); print_r(result); ?>
array_intersect():Description: Compares values across two or more arrays and returns an array containing values from
a1that are present ina3, etc.Code Example:
php <?php $a1 = array("a" => "red", "b" => "green", "c" => "blue", "d" => "yellow"); $a2 = array("e" => "red", "f" => "green", "g" => "blue"); a1, result); ?>
array_key_exists():Description: Verifies whether a specified key exists in an array; returns
trueon match andfalseotherwise.Parameters:
key(Required): Specifies the key to look up.array(Required): Specifies the array to search.Code Example:
php <?php $a = array("Volvo" => "XC90", "BMW" => "X5"); if (array_key_exists("Volvo", $a)) { echo "Key exists!"; } else { echo "Key does not exist!"; } ?>
array_map():Description: Passes each element of an array to a user-defined callback function, returning a transformed array containing the modified elements.
Code Example:
php <?php function myfunction(v) { return(v * $v); } $a = array(1, 2, 3, 4, 5); print_r(array_map("myfunction", $a)); ?>
array_merge():Description: Merges elements from one or more arrays sequentially into a single combined array.
Parameters:
array1(Required): The initial array to merge into.array2(Optional): Second array to merge.array3,...(Optional): Additional arrays to append.Code Example:
php <?php $a1 = array("red", "green"); a1, $a2)); ?>
array_multisort():Description: Sorts multiple arrays simultaneously or sorts a multi-dimensional array. It sorts the primary array first; subsequent arrays follow the order of the first. When identical values occur in the primary array, secondary arrays determine tiebreakers.
Code Example:
php <?php $a = array("Dog", "Cat", "Horse", "Bear", "Zebra"); array_multisort(a); ?>
Array Sorting Algorithms and Directives
Sorting Overview:
Array elements can be sorted in alphabetical or numerical sequence, ascending or descending.
Key distinctions determine which sort function to use:
Type of array: Indexed versus Associative.
Target sorting criteria: Value versus Key.
Direction: Ascending versus Descending.
Sorting Functions Summary:
sort(): Sorts indexed arrays in ascending order.rsort(): Sorts indexed arrays in descending order.asort(): Sorts associative arrays in ascending order according to value.ksort(): Sorts associative arrays in ascending order according to key.arsort(): Sorts associative arrays in descending order according to value.krsort(): Sorts associative arrays in descending order according to key.
Ascending Order on Indexed Arrays (
sort()):Alphabetical sorting implementation:
php <?php letters); ?>
Numerical sorting implementation:
php <?php grade); ?> Descending Order on Indexed Arrays (
rsort()):Alphabetical sorting implementation:
php <?php letters); ?>
Numerical sorting implementation:
php <?php grade); ?> Ascending Order by Value for Associative Arrays (
asort()):Preserves key-value associations while ordering elements from lowest to highest value:
php <?php score); ?>
Ascending Order by Key for Associative Arrays (
ksort()):Orders elements alphabetically or numerically by the keys themselves in ascending order:
php <?php score); ?>
Descending Order by Value for Associative Arrays (
arsort()):Preserves key-value associations while ordering elements from highest to lowest value:
php <?php score); ?>
Descending Order by Key for Associative Arrays (
krsort()):Orders elements by keys in descending order:
php <?php score); ?>