In computer science, an array is a data structure that consists of multiple elements which are uniquely identified by the keys of the array. PHP arrays help manage data as a list.
Read Also: Find Array Length in PHP
Index
There are three types of arrays in PHP, as mentioned below.
Must Read: How to Sort Array in PHP [Explained With Examples]
In a PHP array, the index is represented by a number, and it 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 and White
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
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 an 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'] . "<br>"; echo "Marks for Neha in maths : "; echo $marks['Neha']['maths'] . "<br>"; ?>
Output
Marks for Riya in physics : 95 Marks for Neha in maths : 97
Read More: PHP Array Functions
These are the different types of arrays that are beneficial in learning PHP programming. We hope you have gained a basic understanding of PHP arrays. In case, you are facing some problems related to other concepts of PHP programming, do refer to our other blogs.
Enjoy Programming 🙂
There is a reason big-name companies like CNN use WordPress. WordPress is a popular content…
In this tutorial, I'm going to show you how to install MySQL on your computer.…
Download Turbo C++ for windows 10 in just 7 Mb and run your first C++…
We can redirect any webpage to any other or redirect the whole domain or website…
There are lots of methods to redirect pages, like refresh-redirect from META tag, redirect from…
Include files in PHP are used in appending various global or config files. We can…