⇧
vadnica-logo
Editor My Blog Password Manager Finance My Services About the Project Telegram O meni O meni

PHP Arrays

An array is a special variable that can hold multiple values under a single name. You can then easily access these values by referring to an index number or a named key. In PHP, we distinguish three types of arrays: Indexed arrays (with a numeric index), Associative arrays (with named keys), and Multidimensional arrays (arrays containing other arrays). Elements can be of any data type: strings, numbers, objects, or even functions.

EXAMPLE
RESULT
The result will be displayed here...

Indexed Arrays and Numeric Lookup

Indexed arrays use numbers (indexes) to access their elements. A crucial rule that every beginner must master is that **counting always starts with index number 0**, and not 1. These arrays are ideal for lists of items where order matters, such as user lists, database rows, or simple shopping lists.

Associative Arrays (Key => Value)

Instead of default numbers, associative arrays allow us to arbitrarily assign a custom, **named key** (String) to each element. This is done using the assignment operator =>. Associative arrays are extremely powerful for representing structured records (e.g., car details where keys are brand, model, and year), making the code much more readable and logical.

Multidimensional Arrays and Matrix Data

Simply put, a multidimensional array is "an array that contains one or more other arrays inside it". PHP supports nesting arrays to any depth (two-dimensional, three-dimensional, etc.). These structures are most commonly used to store complex tabular data, matrices, or data structures retrieved from relational databases.

Concept / Operation Description Example (Code for Simulator)
Indexed Arrays In indexed arrays, each element is automatically assigned a sequential numeric index. $cars = ["Audi", "BMW", "Volvo"]; echo $cars[1]; // Outputs BMW
Changing Value by Index To modify the value of a specific element, refer directly to its index number. $colors = ["red", "green"]; $colors[1] = "blue"; print_r($colors);
Looping Through Indexed Array To iterate through and print all values of an indexed array, use a foreach loop. $fruits = ["Apple", "Banana"]; foreach ($fruits as $f) { echo $f . " "; }
Index Number The key of an indexed array is always an integer, and the default value of the first element is index 0. $t = ["A", "B"]; echo "First index is: " . key($t); // 0
Associative Arrays Associative arrays use named text keys that are assigned to elements manually. $age = ["Peter" => 35, "Ana" => 28]; echo $age["Ana"];
Accessing Associative Arrays To access a target value inside an associative array, refer to its key name enclosed in quotes. $person = ["name" => "John"]; echo $person["name"];
Changing Value by Key To update or modify an element value in an associative array, refer to its key name. $prices = ["coffee" => 1.5]; $prices["coffee"] = 1.8; echo $prices["coffee"];
Looping Through Associative Array Using foreach ($t as $k => $v) allows you to easily print both the keys and their values. $t = ["USA" => "Washington"]; foreach($t as $k => $v) { echo "$k: $v"; }
Multi-line Array Line breaks do not matter when declaring arrays, so elements can be written across multiple lines for better clarity. $t = [
  "A",
  "B"
]; print_r($t);
Trailing Commas A comma after the last item in an array is officially allowed in PHP and prevents errors when appending new rows later. $t = ["one", "two",]; echo count($t); // Outputs 2
Array Keys When creating indexed arrays, keys are generated automatically if they are not explicitly declared. $t = ["X", "Y"]; print_r(array_keys($t));
Declaring Empty Array An array can be initialized completely empty, and items can be dynamically appended to it later in the script. $t = []; $t[] = "First"; print_r($t);
Mixing Array Keys PHP permits mixing numeric indices and named associative keys seamlessly within the exact same array. $t = [0 => "A", "name" => "B"]; echo $t[0] . " " . $t["name"];
Accessing Array Element Access elements via square bracket syntax, supplying the corresponding index or key identifier. $t = ["data"]; echo $t[0];
Double or Single Quotes When accessing associative keys, you can use single or double quotes interchangeably; the effect is identical. $t = ["k" => 1]; echo $t['k'] . $t["k"];
Execute Functional Element Array elements can store any data type, including anonymous functions, which can be triggered directly. $t = [function() { return "Hello"; }]; echo $t[0]();
Updating Element in Array Supplying an existing key or index overrides the previous data with the newly specified value. $t = ["old"]; $t[0] = "new"; echo $t[0];
Updating Element in Loop To modify values directly within a foreach loop, prepend a reference operator & to the value variable. $t = [1, 2]; foreach($t as &$v) { $v *= 10; } print_r($t);
Adding Element to Array To push an element onto the end of an indexed array, simply use empty square brackets []. $t = ["A"]; $t[] = "B"; print_r($t); // "B" gets index 1
Adding Element to Associative Array Simply write the new named key inside square brackets and assign the desired value to it. $t = ["a" => 1]; $t["b"] = 2; print_r($t);
Adding Multiple Items (array_push) To append one or more elements to the end of an indexed array simultaneously, use the array_push() function. $t = [1]; array_push($t, 2, 3); print_r($t);
Adding Items to Associative Array (+=) To merge or add missing key-value pairs into an associative array, you can make use of the += operator. $t = ["a" => 1]; $t += ["b" => 2, "c" => 3]; print_r($t);
Removing Element from Array To discard an item from an indexed array and automatically normalize the remaining numerical offsets, use array_splice(). $t = ["A", "B", "C"]; array_splice($t, 1, 1); print_r($t); // Removes B
Removing Multiple Elements By tweaking the length argument within the array_splice() function, you can clear any number of consecutive elements. $t = [1, 2, 3, 4]; array_splice($t, 1, 2); print_r($t); // Removes 2 and 3
Removing from Associative Array To wipe a specific element or custom key out of an associative array completely, use the built-in unset() function. $t = ["a" => 1, "b" => 2]; unset($t["a"]); print_r($t);
Using array_diff() Function You can leverage array_diff() to filter and exclude specific values based on a comparison against a secondary array. $t = ["A", "B", "C"]; $res = array_diff($t, ["B"]); print_r($res);
Removing First Element The array_shift() function pulls the initial item out of the array and shifts all succeeding indices downwards. $t = ["A", "B"]; echo array_shift($t); // Outputs A
Removing Last Element The array_pop() function truncates and returns the very last element of the selected array. $t = ["A", "B"]; echo array_pop($t); // Outputs B
Sorting in Ascending Order The sort() function reorders elements of an indexed array in ascending alphabetical or numerical order. $t = ["B", "A", "C"]; sort($t); print_r($t);
Sorting in Descending Order The rsort() function reorders items of an indexed array in reverse (descending) alphabetical or numerical sequence. $t = [1, 3, 2]; rsort($t); print_r($t);
Sorting by Value (asort) The asort() function sorts an associative array in ascending order by values while preserving key relationships. $t = ["John" => 35, "Ana" => 25]; asort($t); print_r($t);
Sorting by Key (ksort) The ksort() function sorts an associative array in ascending order based on its key index strings. $t = ["B" => 2, "A" => 1]; ksort($t); print_r($t);
Sorting by Value Descending (arsort) The arsort() function sorts an associative array in descending order according to its values. $t = ["John" => 35, "Ana" => 25]; arsort($t); print_r($t);
Sorting by Key Descending (krsort) The krsort() function sorts an associative array in descending order based on its key index strings. $t = ["A" => 1, "B" => 2]; krsort($t); print_r($t);
Two-Dimensional Array Represents an array of arrays. You access nested elements using successive pairs of square brackets. $matrix = [[1, 2], [3, 4]]; echo $matrix[1][0]; // Row 1, column 0 -> Outputs 3

PHP Array Functions

Array functions allow us to access and manipulate arrays effectively. Both simple and multidimensional arrays are fully supported. These array functions are part of the PHP core, meaning no additional installation is required to use them.

Found: -
Function Name Description Example (Code for Simulator)
array() Creates a new array. $t = array(1, 2, 3); print_r($t);
array_change_key_case() Changes all keys in an array to lowercase or uppercase. $t = ["Name" => 1]; print_r(array_change_key_case($t, CASE_LOWER));
array_chunk() Splits an array into chunks of a specified size. $t = [1, 2, 3, 4]; print_r(array_chunk($t, 2));
array_column() Returns the values from a single column in the input (multidimensional) array. $u = [["id"=>1, "n"=>"A"], ["id"=>2, "n"=>"B"]]; print_r(array_column($u, "n"));
array_combine() Creates an array by using one array for keys and another for its values. $k = ["a", "b"]; $v = [1, 2]; print_r(array_combine($k, $v));
array_count_values() Counts all the values of an array. $t = ["A", "B", "A"]; print_r(array_count_values($t));
array_diff() Compares arrays and returns the difference (compares values only). print_r(array_diff([1, 2, 3], [1, 2])); // Outputs 3
array_diff_assoc() Compares arrays and returns the difference (compares both keys and values). print_r(array_diff_assoc(["a"=>1, "b"=>2], ["a"=>1, "b"=>5]));
array_diff_key() Compares arrays and returns the difference (compares keys only). print_r(array_diff_key(["a"=>1, "b"=>2], ["a"=>5]));
array_diff_uassoc() Compares arrays and returns the difference (keys and values) using a user-defined key comparison function. print_r(array_diff_uassoc([1,2], [1], "strcasecmp"));
array_diff_ukey() Compares arrays and returns the difference (keys only) using a user-defined key comparison function. print_r(array_diff_ukey(["a"=>1], ["b"=>2], "strcasecmp"));
array_fill() Fills an array with values starting from a specified index offset. print_r(array_fill(0, 3, "PHP")); // Outputs PHP 3 times
array_fill_keys() Fills an array with values, specifying keys explicitly. print_r(array_fill_keys(["a", "b"], 100));
array_filter() Filters elements of an array using a callback function. print_r(array_filter([1, 2, 3, 4], function($v){ return $v % 2 == 0; }));
array_flip() Flips/Exchanges all keys with their associated values in an array. $t = ["a" => "v"]; print_r(array_flip($t)); // "v" becomes the key
array_intersect() Compares arrays and returns the matches/intersection (compares values only). print_r(array_intersect([1, 2, 3], [2, 3, 4])); // Outputs 2, 3
array_intersect_assoc() Compares arrays and returns the matches (compares both keys and values). print_r(array_intersect_assoc(["a"=>1], ["a"=>1, "b"=>2]));
array_intersect_key() Compares arrays and returns the matches (compares keys only). print_r(array_intersect_key(["a"=>1, "b"=>2], ["a"=>5]));
array_intersect_uassoc() Compares arrays and returns the matches (keys and values) using a user-defined key comparison function. print_r(array_intersect_uassoc(["a"=>1], ["a"=>1], "strcasecmp"));
array_intersect_ukey() Compares arrays and returns the matches (keys only) using a user-defined key comparison function. print_r(array_intersect_ukey(["a"=>1], ["a"=>2], "strcasecmp"));
array_key_exists() Checks if the specified key exists in the array (returns true/false). var_dump(array_key_exists("name", ["name" => "Borut"]));
array_keys() Returns all the keys or index positions of an array. print_r(array_keys(["a" => 1, "b" => 2]));
array_map() Sends each element of an array to a user-defined function to return completely new values. print_r(array_map(function($v){ return $v * 2; }, [1, 2, 3]));
array_merge() Merges one or more arrays into a single combined array. print_r(array_merge([1, 2], [3, 4]));
array_merge_recursive() Merges one or more arrays recursively (combines matching string keys into a sub-array). print_r(array_merge_recursive(["a"=>1], ["a"=>2]));
array_multisort() Sorts multiple arrays at once, or a multidimensional array structure. $t = [3, 1, 2]; array_multisort($t); print_r($t);
array_pad() Inserts a specified number of items with a specified value into an array. print_r(array_pad([1, 2], 4, 0)); // Returns [1, 2, 0, 0]
array_pop() Deletes and returns the very last element of an array. $t = [1, 2, 3]; echo array_pop($t); // Outputs 3
array_product() Calculates the product of all numeric values within an array. echo array_product([2, 3, 4]); // 2 * 3 * 4 = 24
array_push() Inserts one or more elements onto the end of an array. $t = [1]; array_push($t, 2, 3); print_r($t);
array_rand() Returns one or more random keys out of an array. $t = ["a"=>1, "b"=>2, "c"=>3]; echo array_rand($t);
array_reduce() Reduces an array to a single scalar value iteratively using a custom callback function. echo array_reduce([1,2,3], function($c, $v){ return $c + $v; }, 0);
array_replace() Replaces the values of the first array with values from following arrays with matching keys. print_r(array_replace(["A", "B"], [0 => "X"])); // X replaces A
array_replace_recursive() Replaces the values of the first array with values from following arrays recursively (in depth). print_r(array_replace_recursive([["A"]], [["X"]]));
array_reverse() Returns an array with elements in reverse order. print_r(array_reverse([1, 2, 3])); // Returns [3, 2, 1]
array_search() Searches an array for a specified value and returns the matching key if successful. echo array_search("BMW", ["a" => "Audi", "b" => "BMW"]); // b
array_shift() Removes and returns the very first element from an array (and re-indexes numeric keys). $t = [10, 20]; echo array_shift($t); // Outputs 10
array_slice() Extracts a specified slice of an array based on offset and length. print_r(array_slice(["A", "B", "C", "D"], 1, 2)); // B, C
array_splice() Removes selected elements from an array and replaces them with new ones optionally. $t = [1, 2, 3]; array_splice($t, 1, 1, [99]); print_r($t);
array_sum() Calculates the total sum of all values inside an array. echo array_sum([10, 20, 30]); // Outputs 60
array_udiff() Compares arrays and returns the difference of values using a custom value comparison function. print_r(array_udiff([2, 3], [3], function($a,$b){return $a-$b;}));
array_udiff_assoc() Compares arrays and returns the difference (keys and values) using a custom value comparison function. print_r(array_udiff_assoc(["a"=>1], ["a"=>2], function($a,$b){return $a-$b;}));
array_udiff_uassoc() Compares arrays and returns the difference using two custom functions for keys and values comparison. print_r(array_udiff_uassoc([1], [1], "strcasecmp", "strcasecmp"));
array_uintersect() Compares arrays and returns the matches of values using a custom value comparison function. print_r(array_uintersect([1,2], [2], function($a,$b){return $a-$b;}));
array_uintersect_assoc() Compares arrays and returns the matches (keys and values) using a custom value comparison function. print_r(array_uintersect_assoc(["a"=>1], ["a"=>1], function($a,$b){return $a-$b;}));
array_uintersect_uassoc() Compares arrays and returns the matches using two custom functions for keys and values comparison. print_r(array_uintersect_uassoc([1], [1], "strcasecmp", "strcasecmp"));
array_unique() Removes duplicate values from an array, keeping unique entries only. print_r(array_unique([1, 2, 2, 3, 1])); // [1, 2, 3]
array_unshift() Prepends one or more elements to the very beginning of an array. $t = [2, 3]; array_unshift($t, 1); print_r($t);
array_values() Returns all the values of an array, resetting keys to sequential numbers starting from 0. print_r(array_values(["a" => "X", "b" => "Y"]));
array_walk() Applies a user-defined callback function to every individual item in an array. $t = [1, 2]; array_walk($t, function(&$v){ $v += 10; }); print_r($t);
array_walk_recursive() Applies a user-defined function recursively to every item in an array (including nested sub-arrays). $t = [1, [2]]; array_walk_recursive($t, function($v){ echo $v; });
arsort() Sorts an associative array in descending order according to its values (maintaining key associations). $t = ["a"=>1, "b"=>5]; arsort($t); print_r($t);
asort() Sorts an associative array in ascending order according to its values (maintaining key associations). $t = ["a"=>5, "b"=>1]; asort($t); print_r($t);
compact() Creates an associative array from variable names and their current values. $name = "Borut"; $res = compact("name"); print_r($res);
count() Returns the total number of elements contained inside an array. echo count([1, 2, 3, 4]); // Outputs 4
current() Returns the current element highlighted by the internal pointer of an array. $t = ["A", "B"]; echo current($t); // A
end() Sets the internal array pointer to its very last element and returns it. $t = ["A", "B", "C"]; echo end($t); // C
extract() Imports array keys as individual local variables into the current scope symbol table. extract(["x" => 99]); echo $x; // Outputs 99
in_array() Checks if a specific value exists anywhere within the array (returns true/false). var_dump(in_array("v", ["a", "v", "c"]));
key() Fetches the key identifier highlighted by the current internal array pointer. $t = ["a" => 1, "b" => 2]; next($t); echo key($t); // b
krsort() Sorts an associative array in descending order based on its keys index strings. $t = ["a"=>1, "b"=>2]; krsort($t); print_r($t);
ksort() Sorts an associative array in ascending order based on its keys index strings. $t = ["b"=>2, "a"=>1]; ksort($t); print_r($t);
list() Assigns values from an array to a list of separate custom variables. list($first, $second) = [10, 20]; echo $first; // 10
natcasesort() Sorts an array using a "natural order" human algorithm (case-insensitive block). $t = ["img12", "IMG2", "img1"]; natcasesort($t); print_r($t);
natsort() Sorts an array using a "natural order" human algorithm (case-sensitive block). $t = ["picture10", "picture2", "picture1"]; natsort($t); print_r($t);
next() Advances the internal pointer of an array to the succeeding item and outputs it. $t = [10, 20]; echo next($t); // Outputs 20
pos() Official alias wrapper for the current() function. Returns the active pointer element. $t = ["X", "Y"]; echo pos($t); // X
prev() Rewinds the internal array pointer to the preceding item and returns it. $t = [10, 20]; next($t); echo prev($t); // 10
range() Creates an array containing a sequential range of elements (numbers or letters). print_r(range(1, 5)); // Spawns [1, 2, 3, 4, 5]
reset() Resets the internal array pointer back to the very first item and returns its data. $t = [1, 2, 3]; next($t); echo reset($t); // 1
rsort() Sorts an indexed array in descending order, resetting all internal index numbers. $t = [1, 3, 2]; rsort($t); print_r($t);
shuffle() Shuffles all sequential elements inside an array into a completely randomized distribution. $t = [1, 2, 3, 4]; shuffle($t); print_r($t);
sizeof() Official alias wrapper for the count() function. Returns total array length. echo sizeof([1, 2, 3]); // Outputs 3
sort() Sorts an indexed array in ascending order, resetting all internal index numbers. $t = [3, 1, 2]; sort($t); print_r($t);
uasort() Sorts an array with a user-defined comparison function while preserving existing key structures. $t=["a"=>3,"b"=>1]; uasort($t, function($a,$b){return $a-$b;}); print_r($t);
uksort() Sorts an array by its keys using a user-defined custom comparison function. $t=["b"=>1,"a"=>2]; uksort($t, "strcasecmp"); print_r($t);
usort() Sorts an array by its values using a custom function, discarding old keys for new index numbers. $t=[3,1,2]; usort($t, function($a,$b){return $a-$b;}); print_r($t);