Php Indexed Associative And Multidimensional Arrays Complete Guide
Understanding the Core Concepts of PHP Indexed, Associative, and Multidimensional Arrays
Indexed Arrays
Indexed arrays store elements in a continuous sequence starting from index 0. Each element in an indexed array is associated with a numeric index.
Creating Indexed Arrays:
$array = array("apple", "banana", "cherry");
// Or using short array syntax introduced in PHP 5.4
$array = ["apple", "banana", "cherry"];
Accessing Elements: Elements in an indexed array are accessed using their numeric index.
echo $array[1]; // Outputs "banana"
Modifying Elements: You can change the value of an element by assigning it a new value using its index.
$array[1] = "orange";
echo $array[1]; // Outputs "orange"
Adding Elements:
New elements can be added to the end of the array or at specific positions by using array functions like array_push()
or direct index assignment.
array_push($array, "mango"); // Adds "mango" to the end
// Or
$array[] = "grape"; // Adds "grape" to the end
Important Functions:
- count(): Returns the number of elements in the array.
- array_push() / []: Adds one or more elements to the end of an array.
- array_pop(): Removes the last element from an array and returns it.
- sort() / rsort(): Sorts the array in ascending or descending order respectively.
Example:
$fruits = ["apple", "banana", "cherry"];
sort($fruits); // Sorts in ascending order: [apple, banana, cherry]
echo count($fruits); // Outputs 3
array_push($fruits, "date");
print_r($fruits); // Outputs Array ( [0] => apple [1] => banana [2] => cherry [3] => date )
Associative Arrays
Associative arrays in PHP have named keys defined by the programmer. This makes it easier to understand and maintain the code by using meaningful keys.
Creating Associative Arrays:
$assocArray = array(
"color" => "red",
"type" => "apple",
"number" => 5
);
// Or using short array syntax
$assocArray = [
"color" => "red",
"type" => "apple",
"number" => 5
];
Accessing Elements: Elements are accessed using their string key.
echo $assocArray["color"]; // Outputs "red"
Modifying Elements: You can change the value of an element by assigning a new value using its key.
$assocArray["color"] = "green";
echo $assocArray["color"]; // Outputs "green"
Adding Elements: New elements can be added by specifying a new key or directly using the array syntax.
$assocArray["size"] = "small"; // Adding a new element with key "size"
Important Functions:
- count(): Returns the number of elements in the array.
- array_keys() / array_values(): Returns all the keys/values of an array.
- ksort() / krsort(): Sorts the array by key in ascending or descending order respectively.
- asort() / arsort(): Sorts the array by values in ascending or descending order respectively.
Example:
$fruits = [
"color" => "red",
"type" => "apple",
"number" => 5
];
ksort($fruits); // Sorts by keys: ["color" => "red", "number" => 5, "type" => "apple"]
print_r(array_keys($fruits)); // Outputs: Array ( [0] => color [1] => number [2] => type )
print_r(array_values($fruits)); // Outputs: Array ( [0] => red [1] => 5 [2] => apple )
Multidimensional Arrays
Multidimensional arrays are arrays containing one or more arrays as their elements. They are useful for storing complex data sets where data can be categorized into different groups.
Creating Multidimensional Arrays:
$multiArray = array(
"fruits" => array(
"color" => "red",
"type" => "apple"
),
"vegetables" => array(
"color" => "green",
"type" => "carrot"
)
);
// Or using short array syntax
$mDArray = [
"fruits" => [
"color" => "red",
"type" => "apple"
],
"vegetables" => [
"color" => "green",
"type" => "carrot"
]
];
Accessing Elements: Elements in a multidimensional array are accessed using nested keys or indices.
echo $multiArray["fruits"]["color"]; // Outputs "red"
Modifying Elements: Values can be changed using nested keys or indices.
$multiArray["fruits"]["color"] = "yellow";
echo $multiArray["fruits"]["color"]; // Outputs "yellow"
Adding Elements: New arrays or elements can be added by specifying new keys or indices.
$multiArray["dairy"] = [
"type" => "milk",
"fat" => "whole"
];
Important Functions:
- count(): Can be used with the
COUNT_RECURSIVE
flag to get the total number of elements in a multidimensional array. - array_merge_recursive(): Combines two or more arrays recursively.
- unset(): Used to delete elements from arrays.
Example:
Online Code run
Step-by-Step Guide: How to Implement PHP Indexed, Associative, and Multidimensional Arrays
1. Indexed Arrays
Step-by-Step Guide:
Creating an Indexed Array:
An indexed array is an array with numeric index values automatically assigned to elements.
Example:
<?php // Creating an indexed array using array() syntax $colors = array("Red", "Green", "Blue"); // Creating an indexed array using shorthand array syntax (since PHP 5.4) $fruits = ["Apple", "Banana", "Cherry"]; // Printing the arrays print_r($colors); print_r($fruits); ?>
When you run this code, it will output:
Array ( [0] => Red [1] => Green [2] => Blue ) Array ( [0] => Apple [1] => Banana [2] => Cherry )
Accessing Elements of an Indexed Array:
You can access elements by their index using square brackets.
Example:
<?php // Accessing elements by index echo $colors[0]; // Outputs: Red echo $fruits[2]; // Outputs: Cherry ?>
Modifying Elements of an Indexed Array:
You can change an existing element by assigning a new value to its index.
Example:
<?php // Modifying an element $colors[1] = "Yellow"; print_r($colors); // Outputs: Array ( [0] => Red [1] => Yellow [2] => Blue ) ?>
Adding Elements to an Indexed Array:
Use square brackets
[]
with no index specified to add elements to the end of the array.Example:
<?php // Adding an element to the end of the array $fruits[] = "Date"; print_r($fruits); // Outputs: Array ( [0] => Apple [1] => Banana [2] => Cherry [3] => Date ) ?>
2. Associative Arrays
Step-by-Step Guide:
Creating an Associative Array:
An associative array is an array with named index keys (keys can be strings).
Example:
<?php // Creating an associative array using array() syntax $studentScores = array("Alice" => 85, "Bob" => 90, "Charlie" => 78); // Creating an associative array using shorthand array syntax (since PHP 5.4) $studentAges = ["Alice" => 20, "Bob" => 22, "Charlie" => 19]; // Printing the arrays print_r($studentScores); print_r($studentAges); ?>
When you run this code, it will output:
Array ( [Alice] => 85 [Bob] => 90 [Charlie] => 78 ) Array ( [Alice] => 20 [Bob] => 22 [Charlie] => 19 )
Accessing Elements of an Associative Array:
Access elements by their key using square brackets.
Example:
<?php // Accessing elements by key echo $studentScores["Alice"]; // Outputs: 85 echo $studentAges["Bob"]; // Outputs: 22 ?>
Modifying Elements of an Associative Array:
Change an existing element by assigning a new value to its key.
Example:
<?php // Modifying an element $studentScores["Bob"] = 95; print_r($studentScores); // Outputs: Array ( [Alice] => 85 [Bob] => 95 [Charlie] => 78 ) ?>
Adding Elements to an Associative Array:
Add elements by specifying a new key and value.
Example:
<?php // Adding an element $studentAges["David"] = 21; print_r($studentAges); // Outputs: Array ( [Alice] => 20 [Bob] => 22 [Charlie] => 19 [David] => 21 ) ?>
3. Multidimensional Arrays
Step-by-Step Guide:
Creating Multidimensional Arrays:
A multidimensional array is an array containing one or more arrays.
Example:
<?php // Creating a multidimensional array (array of arrays) $students = [ ["name" => "Alice", "age" => 20, "scores" => [85, 90]], ["name" => "Bob", "age" => 22, "scores" => [95, 88]], ["name" => "Charlie", "age" => 19, "scores" => [78, 82]], ]; // Printing the multidimensional array print_r($students); ?>
When you run this code, it will output:
Array ( [0] => Array ( [name] => Alice [age] => 20 [scores] => Array ( [0] => 85 [1] => 90 ) ) [1] => Array ( [name] => Bob [age] => 22 [scores] => Array ( [0] => 95 [1] => 88 ) ) [2] => Array ( [name] => Charlie [age] => 19 [scores] => Array ( [0] => 78 [1] => 82 ) ) )
Accessing Elements of a Multidimensional Array:
Access nested elements by specifying multiple indices or keys.
Example:
<?php // Accessing elements echo $students[0]["name"]; // Outputs: Alice echo $students[1]["scores"][1]; // Outputs: 88 ?>
Modifying Elements of a Multidimensional Array:
Change nested elements by assigning new values to their indices or keys.
Example:
<?php // Modifying elements $students[1]["age"] = 23; $students[2]["scores"][0] = 80; print_r($students); ?>
Adding Elements to a Multidimensional Array:
Add new arrays or elements by specifying new indices or keys.
Example:
Login to post a comment.