PHP Arrays

PHP array is an ordered map (contains value on the basis of key). It is used to hold multiple values of similar type in a single variable.

Advantage of PHP Array

Less Code: We don’t need to define multiple variables.

Easy to traverse: By the help of single loop, we can traverse all the elements of an array.

Sorting: We can sort the elements of array.

PHP Array Types

There are 3 types of array in PHP.

  1. Indexed Array
  2. Associative Array
  3. Multidimensional Array
  4. PHP Indexed Array

    PHP index is represented by number which starts from 0. We can store number, string and object in the PHP array. All PHP array elements are assigned to an index number by default.

    There are two ways to define indexed array:

    1st way:

2nd way:

Example

File: array1.php

Output:

Season are: summer, winter, spring and autumn

File: array2.php

Output:

Season are: summer, winter, spring and autumn

PHP Associative Array

We can associate name with each array elements in PHP using => symbol.

There are two ways to define associative array:

1st way:

2nd way:

Example

File: arrayassociative1.php

Output:

File: arrayassociative2.php

Output:

PHP Multidimensional Array

PHP multidimensional array is also known as array of arrays. It allows you to store tabular data in an array. PHP multidimensional array can be represented in the form of matrix which is represented by row * column.

Definition

PHP Multidimensional Array Example

Let’s see a simple example of PHP multidimensional array to display following tabular data. In this example, we are displaying 3 rows and 3 columns.

Id Name Salary
1 sonoo 400000
2 john 500000
3 rahul 300000

File: multiarray.php

Output:

Please follow and like us:

Leave a Reply

Your email address will not be published. Required fields are marked *