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, the 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 the cricketer’s name and then printed with the 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
  • Associative Arrays
  • Multidimensional Arrays

Indexed (Numeric) Arrays

The 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 them. 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 print the number of days for learning Java and Android respectively.

Multidimensional Arrays

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

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

Here’s the output,

PHP Multidimensional Arrays

Here, you can see two-dimensional arrays with names and keys associated with them i.e. associative arrays. 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 Variables
Run your first PHP program in XAMPP Server on localhost
Studyopedia Editorial Staff
Studyopedia Editorial Staff
[email protected]

We work to create programming tutorials for all.

No Comments

Post A Comment

Discover more from Studyopedia

Subscribe now to keep reading and get access to the full archive.

Continue reading