PHP Arrays

PHP Arrays

Arrays store multiple values in a variable. For example, to store 10 numbers, you can define an array of length 10, instead of defining 10 variables. PHP arrays include Indexed Arrays, Associative Arrays, and Multi-dimensional Arrays.

In PHP, array() function is used to create an array. Let’s see an example,

Here’s the output,

PHP arrays
As shown above, an array is created with cricketers name and then printed with echo output statement. Here, cricketer names are printed using array indexing i.e. $cricketers[0] for cricketer Sachin, $cricketers[0] for cricketer Virat, and $cricketers[0] for cricketer Rohit,

Now, we will learn about the types of arrays in PHP.

Indexed (Numeric) Arrays

Indexed array consists of numeric index, so they are also called Numeric arrays. The array index is a number and the default index starts from 0.

Here’s an example, with an indexed array, topics. The array assigns two elements, which are the names of topics,

Here’s the output,

PHP Indexed Arrays

Here, topic names are printed using array indexing i.e. $topics[0] for topic Java, and $topics[1] for topic Android,

Associative Arrays

These are arrays that have named keys associated with it. Here’s an example showing named keys associated with Java and Android,

Here’s the output,

PHP Associative Arrays

As shown above, the names keys associated with the array prints the number of days for learning Java and Android respectively.

Multidimensional Arrays

An array with one or more than one array is known as Multidimensional array. Two dimensional arrays is a multi-dimensional array and also considered as array of arrays.

Here’s an example of two-dimensional arrays, with associative array,

Here’s the output,

PHP Multidimensional Arrays

Here, you can see two dimensional arrays with names keys associated with it i.e. associative array. It shows the points for two cricketers in all three formats i.e. testcricket, ODI, and T20. Using multi-dimensional arrays, we have shown it for 2 cricketers i.e. two dimensional arrays.

Here, you can learn about another example. Now, we will print all the values, with an additional array for cricketer David Warner,

 Test CricketODIT20
Virat Kohli515370
Joe Root533738
David Warner504245


PHP Decision Making Statements
PHP String Handling
Studyopedia Editorial Staff
Studyopedia Editorial Staff
[email protected]

We work to create free tutorials for all.

No Comments

Post A Comment