Array in PHP with example: Numeric and Multidimensional Associative

Array in PHP: A array is an information structure that stores at least one comparative kind of values in a single value. For example, on the off chance that you need to store 200 numbers, then as instead of defining 200 variables its simple to define a variety of 200 length.

“An array is an exceptional variable, which can hold more than one value at any given time.”

Create an Array in PHP with example

In PHP, the array() function is used to create an array: array();

There are three(Numeric array – Associative array – Multidimensional array) different kinds of arrays and each array value is accessed using an ID c which is called array index.

The issue is, a variable will hold just a single value. You can store a single number in a variable, or a single string. An array is like an exceptional variable, which can hold more than one number, or more than one string, at once. In the event that you have a list of items (like a list of customer orders, for example), and you need to do something with them, then it would be quite cumbersome to do this:

$Order_Number1 = “Black shoes”;

$Order_Number2 = “Tan shoes”;

$Order_Number3 = “Red shoes”;

$Order_Number4 = “Blue shoes”;

In PHP, there are three types of arrays:

  1. Multidimensional arrays – Arrays containing one or more arrays
  2. Associative arrays – Arrays with named keys
  3. Indexed arrays – Arrays with a numeric index
  • PHP Indexed(Numeric) Arrays

These arrays can store numbers, strings and any object, but their index will be represented by numbers. By default array index starts from zero.

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

Example

Output

  • PHP Associative Arrays

Associative arrays are arrays that use named keys that you assign to them. The associative arrays are very similar to numeric arrays in term of functionality, but they are different in terms of their index. Associative array will have their index as string so that you can establish a strong association between key and values.

To store the salaries of employees in an array, a numerically indexed array would not be the best choice. Instead, we could use the employees’ names as the keys in our associative array, and the value would be their respective salary.

2 ways to define an associative array:

OR:

NOTE − Don’t keep associative array inside double quote while printing otherwise it would not return any value.

Example

Output

  • Multidimensional Arrays

A multi-dimensional array, each element in the main array can also be an array. And each element in the sub-array can be an array, and so on. Values in the multi-dimensional array are accessed using multiple index.

Example

Output

Thanks for reading my article about “Array in PHP with example: Numeric, Associative And Multidimensional Associative”. If you like this article do me favor by sharing it with your friends.

Digital Technology Hub