PHP Arrays

PHP arrays are a type of variable that holds multiple values of the same data type at a time. PHP arrays help manage data as a list.

Read Also: Find Array Length in PHP

Types of Arrays in PHP

There are three types of arrays in PHP, as mentioned below.

  1. Indexed array
  2. Associative array
  3. Multidimensional array

Indexed Array

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

There are different ways to define an indexed array.

$color=array("Red","Green","Blue","White");
$color[0]="Red";  

$color[1]="Green";  

$color[2]="Blue";  

$color[3]="White";

Example

<?php  

$color=array("Red","Green","Blue","White");  

echo "Colors are: $color[0], $color[1], $color[2] and $color[3]";  

?>

Output

Colors are: Red, Green, Blue, White

Associative Array

We can associate the name with each element of the array in PHP using the ‘=>’ symbol.

There are two ways to define an associative array:

// Method 1
$salary=array("Suman"=>"350000","Neha"=>"450000","Riya"=>"200000");
// Method 2
$salary = array();

$salary["Suman"]="350000";  

$salary["Neha"]="450000";  

$salary["Riya"]="200000";

Example

<?php    

$salary=array("Suman"=>"350000","Neha"=>"450000","Riya"=>"200000");    

echo "Suman salary: ".$salary["Suman"]."<br/>";  

echo "Neha salary: ".$salary["Neha"]."<br/>";  

echo "Riya salary: ".$salary["Riya"]."<br/>";  

?>

Output

Suman salary: 350000
Neha salary: 450000
Riya salary: 200000

Multidimensional Array

The multidimensional array is an array in which each element can also be an array. Each element in the sub-array can be an array or further contain array within itself and so on.

Example

<?php
$marks = array(
    "Riya" => array (
      "physics" => 95,
      "maths" => 90,
    ),
    "Neha" => array (
      "physics" => 92,
      "maths" => 97,
    ),
);
echo "Marks for Riya in physics : " ;
echo $marks['Riya']['physics'] . "\n";
echo "Marks for Neha in maths : ";
echo $marks['Neha']['maths'] . "\n";
?>

Output

Marks for Riya in physics : 95
Marks for Neha in maths : 97

Read More: PHP Array Functions

Conclusion

These are the different types of arrays that are beneficial in learning PHP programming. I hope now you have a basic understanding of PHP arrays.

Enjoy Programming 🙂

Leave a Reply

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

Read previous post:
Top 25 SQL Queries Interview Questions
Top 25 SQL Queries Interview Questions for Experienced (Free PDF Download)

If you are preparing for the database administrator (DBA) job? If yes, you are at the perfect spot for getting...

Close