An array is a data structure that stores one or more similar type of values under a single name, and you can access the values by referring to an index number.
For example if you want to store 100 numbers then instead of defining 100 variables its easy to define an array of 100 length.
In PHP, There are three different kind of arrays and each array value is accessed using an ID c which is called array index.
- Indexed arrays – An array with a numeric index. Values are stored and accessed in linear fashion.
- Associative arrays – An array with strings as index. This stores element values in association with key values rather than in a strict linear index order.
- Multidimensional arrays – An array containing one or more arrays and values are accessed using multiple indices.
PHP Indexed Arrays:
These arrays can store numbers, strings and any object but their index will be represented by numbers.
There are two ways to create indexed arrays:
The index can be assigned automatically (index always starts at 0):
or the index can be assigned manually:
Following is the example showing how to create and access numeric arrays.Here we have used array() function to create array.
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5
Value is one
Value is two
Value is three
Value is four
Value is five
PHP Associative Arrays :
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.
There are two ways to create an associative array:
Result of Student1 is 45%
Result of Student2 is 65%
Result of Student3 is 85%
Result of Student1 is low percentage
Result of Student2 is medium percentage
Result of Student3 is high percentage
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.
In this example we create a two dimensional array to store marks of three students in three subjects:
This example is an associative array, you can create numeric array in the same type.
Marks for student1 in physics : 40.
Marks for student2 in maths : 45.
Marks for student3 in chemistry : 39.
Get The Length of an Array – The count() Function :
The count() function is used to return the length (the number of elements) of an array.