• In PHP an array is a type of data structure that allows us to store multiple elements of similar data type under a single variable thereby saving us the effort of creating a different variable for every data.
  • Using their index or key arrays are helpful to create a list of elements of similar types, which can be accessed.
  • Suppose accordingly we want to store five names and print them and it can be easily done by the use of five different string variables.
  • Instead of five string variables, the number rises to a hundred, then it would be really difficult for the developer or user to create so many different variables.
  • Also using an index or a key array comes into play and helps us to store every element within a single variable and also allows easy access.
  • In PHP an array is created using array() function and basically there three types, they are
    1. Indexed array
    2. Associative array
    3. Multidimensional array

Indexed array

  • Indexed array is represented by number which starts from 0 and we can store integer, object and string in the PHP array.
  • By default, all PHP array elements are assigned to an index number.

Sample Code

<?php  
$season=array("January","February","March","April");
echo "Month are: $month[0], $month[1], $month[2] and $month[3]";
?>

Output

Associative Array

  • Associative arrays are similar to the indexed arrays but instead of linear storage, every value can be assigned with a user-defined key of string type.
  • In PHP we can associate name with each array elements by using => symbol.

Sample Code

<?php    
$salary["Venkat"]="350000";
$salary["Kishore"]="450000";
$salary["Nizar"]="200000";
echo "Venkat salary: ".$salary["Venkat"]."<br/>";
echo "Kishore salary: ".$salary["Kishore"]."<br/>";
echo "Nizar salary: ".$salary["Nizar"]."<br/>";
?>

Output

Multidimensional Array

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

Sample Code

$emp = array  
(
array(1,"Venkat",400000),
array(2,"Kishore",500000),
array(3,"Nizar",300000)
);

Output

 

ID

 

Name

 

Salary

 

1

 

Venkat

 

400000

 

2

 

Kishore

 

500000

 

3

 

Nizar

 

300000

Categorized in: