PHP Array

PHP Array – Indexing, Associative, Multidimensional

Posted by

An array is the most important part of any programing language. It is very useful if you work on a large amount of data or fetching and manipulating the database.

In this article, the following topic will be covered:

What are PHP Arrays?

A PHP array is a variable that store single or multiple data type values in a single variable and that can access by index or associate’s name. An array creates using array() function or sqare[] brackets.

Example:

Usage of PHP Arrays:

Easy to manipulate: Adding or removing elements in an array, and reading or changing an element’s value, is easy.
A large amount of data: Through the loop, you can easily reading or changing each element’s value.
Manipulation of Array: PHP gives many in-built functions to merge array, sort array value, and key as well and remove elements, etc.

Types of Array

There are three types of Array:

  1. Index or Numeric Array
  2. Associative Array
  3. Multidimensional Array

Indexing Array

An indexed or numeric array stores a numeric index for every array element.

Syntax:

or

Let’s take an example:

Associative Arrays

Associative array associates with key and value.

Let’s take an example:

In the above example, names are associated with salary.

Multidimensional Arrays

A multidimensional array is a set of arrays. PHP supports two, three, four, etc level of the multidimensional array. Array with more than three levels is difficult to manage.

Syntax:

In the above syntax is a two-dimensional(2D) array.

Let’s take a table of employee and implement it in an array:

Name Age Salary
John 28 50000
Peter 25 40000
Harry 26 45000

Operating on Arrays

PHP has many built-in functions to operate the array. We will apply some of them for operation and also we will use the PHP loop.

1. Print_r: It is used to print the array.

Example:

Output:

2. Var_dump: It shows data type and value as well.
Example:

Output:

3. Count: It is used to count the array.

Example:

Output:

4. Foreach Loop: Foreach Loop is used to print the array.

Example:

Output:

You can print Employee name through For loop.

Sorting Arrays

Sorting is used to order the data in ascending or descending. PHP has the in-built function for sorting the array.

1. sort() : It is used to sort an array in ascending array.

Example:

Output:

2. rsort() : It is used to sort an array in descending order

Output:

3. asort(): It is used to sort the associative array in ascending order.

Output:

4. ksort(): It is used to sort associative in ascending order according to the key.

Output:

Check the article to sort array without in-built function.

 

Leave a Reply

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