Unit 4: Working with Arrays

4th semester

Unit 1 Unit 2 Unit 3 Unit 5 Unit 6 Unit 7 Unit 8 Unit 9
Unit 10

Array

An array stores multiple values in one single variable.A variable is a storage area holding a number or text. The problem is, a variable will hold only one value.An array is a special variable, which can store multiple values in one single variable.An array can hold all your variable values under a single name. And you can access the values by referring to the array name.Each element in the array has its own index so that it can be easily accessed.

Create an Array in PHP

In PHP, the array() function is used to create an array.

 

Types of Array in PHP

There are three types of array in php, which are given below.

  • Indexed/Numeric  arrays – Arrays with a numeric index
  • Associative arrays – Arrays with named keys
  • Multidimensional arrays – Arrays containing one or more arrays

 

i. Numeric Arrays

A numeric array stores each array element with a numeric index. There are two methods to create a numeric array.

  1. In the following example the index are automatically assigned (the index starts at 0):

2. In the following example we assign the index manually:

Example

output
Class 10th Students Harry, Varsha and Gaurav

ii.Associative Arrays

An associative array, each ID key is associated with a value.When storing data about specific named values, a numerical array is not always the best way to do it.With associative arrays we can use the values as keys and assign values to them.
syntax :-
$age = array(“Harry”=>”10”, “Varsha”=>”20”, “Gaurav”=>”30”);
or
$age[‘Harry’] = “10”;
$age[‘Varsha’] = “20”;
$age[‘Gaurav’] = “30”;

iii. multidimensional array

A multidimensional array is an array containing one or more arrays. For a two-dimensional array you need two indices to select an element

Array Example

output

Harry: Marks: 300 Class: 11
Varsha: Marks: 400 Class: 10
Gaurav: Marks: 200 Class: 8
Hitesh: Marks: 220 Class: 8

Sorting an Array

Ordering data in an increasing or decreasing fashion.
i.Sort: Sorting an index array in ascending order.


ii.rsort: Sorting an index array in descending order.

iii.asort: Sorting an associative array in ascending order  according to value.

iv.ksort: Sorting an associative array in ascending order  according to key.

v. arsort: Sorting an associative  array in descending order  according their value.

vi. krsort: Sorting an associative array in descending order  according their key.