0% found this document useful (0 votes)
44 views5 pages

PHP Array Types Explained

There are three types of arrays in PHP: indexed arrays which use numeric indexes; associative arrays which use named keys; and multidimensional arrays which contain one or more arrays. Indexed arrays can be automatically indexed starting from 0 or manually assigned indexes. Associative arrays use named keys assigned to values. Multidimensional arrays contain nested arrays and require multiple indexes to access elements.

Uploaded by

himanshidalal74
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views5 pages

PHP Array Types Explained

There are three types of arrays in PHP: indexed arrays which use numeric indexes; associative arrays which use named keys; and multidimensional arrays which contain one or more arrays. Indexed arrays can be automatically indexed starting from 0 or manually assigned indexes. Associative arrays use named keys assigned to values. Multidimensional arrays contain nested arrays and require multiple indexes to access elements.

Uploaded by

himanshidalal74
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

In PHP, there are three types of arrays:

 Indexed arrays - Arrays with a numeric index


 Associative arrays - Arrays with named keys
 Multidimensional arrays - Arrays containing one or more arrays

PHP Indexed Arrays


PHP Indexed Arrays
There are two ways to create indexed arrays:

The index can be assigned automatically (index always starts at 0), like this:

$cars = array("Volvo", "BMW", "Toyota");

or the index can be assigned manually:

$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";

The following example creates an indexed array named $cars, assigns three
elements to it, and then prints a text containing the array values:

ExampleGet your own PHP Server


<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>

Try it Yourself »
Loop Through an Indexed Array
To loop through and print all the values of an indexed array, you could use
a for loop, like this:

Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);

for($x = 0; $x < $arrlength; $x++) {


echo $cars[$x];
echo "<br>";
}
?>

PHP Associative Arrays


PHP Associative Arrays
Associative arrays are arrays that use named keys that you assign to them.

There are two ways to create an associative array:

$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

or:

$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";

The named keys can then be used in a script:


ExampleGet your own PHP Server
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>

Try it Yourself »

Loop Through an Associative Array


To loop through and print all the values of an associative array, you could use
a foreach loop, like this:

Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

foreach($age as $x => $x_value) {


echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>

PHP Multidimensional Arrays


PHP - Multidimensional Arrays
A multidimensional array is an array containing one or more arrays.

PHP supports multidimensional arrays that are two, three, four, five, or more
levels deep. However, arrays more than three levels deep are hard to manage
for most people.

The dimension of an array indicates the number of indices you need to


select an element.
 For a two-dimensional array you need two indices to select an element
 For a three-dimensional array you need three indices to select an element

PHP - Two-dimensional Arrays


A two-dimensional array is an array of arrays (a three-dimensional array is an
array of arrays of arrays).

First, take a look at the following table:

Name Stock

Volvo 22

BMW 15

Saab 5

Land Rover 17

We can store the data from the table above in a two-dimensional array, like
this:

$cars = array (
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
Now the two-dimensional $cars array contains four arrays, and it has two
indices: row and column.

To get access to the elements of the $cars array we must point to the two
indices (row and column):

ExampleGet your own PHP Server


<?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>";
?>

<?php
for ($row = 0; $row < 4; $row++) {
echo "<p><b>Row number $row</b></p>";
echo "<ul>";
for ($col = 0; $col < 3; $col++) {
echo "<li>".$cars[$row][$col]."</li>";
}
echo "</ul>";
}
?>

Common questions

Powered by AI

In PHP indexed arrays, indices can be assigned automatically or manually. Automatic assignment occurs when you declare the array without specifying indices, such as $cars = array("Volvo", "BMW", "Toyota");, where PHP automatically assigns consecutive numeric indices starting from 0. In contrast, manual assignment allows specifying indices explicitly: $cars[0] = "Volvo"; $cars[1] = "BMW";. This manual assignment gives precise control over index values, which might be necessary when integrating arrays with data that require specific indices. Automatic assignments are generally convenient for sequential datasets .

PHP has three types of arrays: Indexed arrays, Associative arrays, and Multidimensional arrays. Indexed arrays use numeric indices and can be created with automatic or manual index assignment. For example, an indexed array can be created like this: $cars = array("Volvo", "BMW", "Toyota");. Associative arrays use named keys that you assign. For example, $age = array("Peter"=>"35", "Ben"=>"37"); illustrates an associative array where elements are accessed using keys rather than indices. Multidimensional arrays, on the other hand, are arrays that contain one or more arrays, and their structure involves indices that span across dimensions. For example, $cars = array (array("Volvo", 22), array("BMW", 15)); creates a two-dimensional array where each element is accessed using two indices .

Multidimensional arrays in PHP are arrays that contain one or more arrays as their elements. They can be two-dimensional, three-dimensional, or even more complex. For example, a two-dimensional array might look like $cars = array (array("Volvo",22,18), array("BMW",15,13)). Arrays more than three levels deep are considered difficult to manage because of the complexity in keeping track of multiple indices and potentially large nested data structures. This complexity increases the likelihood of errors and makes it harder to visualize and conceptualize data structures within code .

To loop through a PHP indexed array, you use a for loop. Example: $cars = array("Volvo", "BMW", "Toyota"); for($x = 0; $x < count($cars); $x++) { echo $cars[$x]; }. In this context, you access elements directly by using numeric indices. For associative arrays, you instead use a foreach loop to iterate through key-value pairs. For example: $age = array("Peter"=>"35", "Ben"=>"37"); foreach($age as $key => $value) { echo "Key=" . $key . ", Value=" . $value; }. The primary difference lies in how elements are accessed: numeric indices vs. named keys .

In PHP, two-dimensional arrays can model a table where each row represents an entity, and each column represents different attributes of that entity. For a dealership scenario, car models can be stored in rows, and attributes such as stock and sold quantities as columns. For example: $cars = array (array("Volvo",22,18), array("BMW",15,13));, where each sub-array stores a car's name, stock number, and sold quantity. This setup allows for quick access and processing of car inventory data by specifying row and attribute index, like $cars[0][1] for the stock number of 'Volvo' .

The count() function in PHP returns the number of elements within an array, which is critical when looping through an indexed array using a for loop. It determines the number of iterations required in the loop by providing the array's length, ensuring that each element is accessed exactly once. For example: $arrlength = count($cars); for($x = 0; $x < $arrlength; $x++) { echo $cars[$x]; }. This approach eliminates the need to hardcode array length, offering flexibility and adaptability to dynamic arrays .

PHP multidimensional arrays facilitate the representation of complex data structures by allowing arrays to nest within each other, effectively modeling more complex hierarchical or tabular data. This is useful for structures like tables, where each row can be an array representing records and each column an attribute or field. A practical example is representing a table of car information: $cars = array (array("Volvo",22,18), array("BMW",15,13));, where each sub-array contains the name, stock number, and sold number of cars. The structure and two indices dimension help segment and access each piece of data separately .

Using named keys in PHP associative arrays allows you to access and manipulate data using descriptive identifiers instead of numeric indices. This significantly improves code readability and maintainability, as the keys can provide meaningful context regarding the data they represent, such as $age['Peter'] = "35"; where 'Peter' provides direct insight into whose age is being represented. This approach also facilitates faster retrieval and manipulation of data based on known keys, enabling you to write code that is more intuitive to understand and easier to maintain and extend, especially in larger data structures .

Associative arrays provide significant advantages over indexed arrays for non-sequential data handling in PHP due to their use of named keys. Named keys eliminate the need to remember numeric indices or to maintain order, allowing data retrieval by descriptive keys that may directly reflect the data's semantics, such as 'age' or 'name'. This leads to more intuitive and readable code, enhances data organization, and facilitates easier data updates and retrievals. For instance, an associative array representing ages, $age = array("Peter"=>"35", "Ben"=>"37"); allows direct access via keys 'Peter' and 'Ben', beneficial for datasets where relationships are better expressed through descriptors rather than position .

The following code demonstrates accessing elements in a two-dimensional PHP array by specifying indices: $cars = array (array("Volvo",22,18), array("BMW",15,13)); echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";. Here, $cars[0][0] accesses the string 'Volvo', $cars[0][1] accesses the integer 22, and so on, by specifying the row and column indices for each element .

You might also like