Types of Arrays
Three different types of the array can be created in PHP. These are numeric array, associative array, and multi-dimensional array. The uses of these arrays are mentioned below.
A. Numeric Array
The index of this array is numeric and the index values of this array are generated sequentially by default. Each array value can be set or get by using the numeric index.
B. Associative Array
The index of this array can be a number or string and the index values of this array may contain different types of string values that are called the key. The ‘=>’ symbol is used to define each key-value pair of this array and each value of the array is accessed by the corrC. esponding key value.
C. Multi-dimensional Array
The array that contains more than one dimension is called a multi-dimensional array. One array contains one or more arrays in a multi-dimensional array. Multi-dimensional numeric arrays and the associative array can be used in PHP.
PHP Array Declaration
The array can be declared by specifying the particular index and value separately. Or by initializing all values at the time of array variable declaration by using the third brackets ([]) or array () function. Three different types of array declarations are shown below.
A. Declare the array by defining the index:
$array1[0] = "Hello";
//Declare a value of an associative array
$array2["name"] = " Fahmida";
B. Declare array by using [] brackets:
$arrvar1 = ['PHP', 'HTML', 'CSS', 'JavaScript'];
//Declare an associative array of three elements by using []
$arrvar1 = ['Personal Home Page' => 'PHP', 'Hypertext Mark-up Language' => 'HTML', 'Cascading Style Sheet' => 'CSS'];
C. Declare array by using array() function
$arrvar1 = array('PHP', 'HTML', 'CSS', 'JavaScript');
//Declare an associative array of three elements by using the array() function
$arrvar1 = array('Personal Home Page' => 'PHP', 'Hypertext Mark-up Language' => 'HTML', 'Cascading Style Sheet' => 'CSS');
Example 1: Accessing Numeric Array Without Loop
Create a PHP file with the following script that will create three arrays of the numeric index in three different ways and access the array values by defining the index. The first array has been created by defining the index and it contains all number values. The second array has been created by using [] brackets and it contains all string values. The third array has been created by using the array() function and it contains different types of data. Next, the three values have been printed by defining the index.
//Create a numeric array of numbers using the index
$arrnum[0] = 70;
$arrnum[1] = 89;
$arrnum[2] = 56;
//Create a numeric array of strings using [] brackets
$arrname = ["Janifer","Jafar", "Jony"];
//Create a numeric array of different values using the array()
$arrmix = array(True, "PHP", 8.1, 100);
//Print the values of the numeric arrays using the index
echo "The value of 2nd index of <b> arrnum </b> :$arrnum[1]<br />";
echo "The value of 1st index of <b> arrname </b> : $arrname[0]<br />";
echo "The value of 3rd index of <b> arrmix <b>: $arrmix[2]";
?>
Output
Open a browser and execute the above script from the server. The following output will appear after executing the script. The value of the 2nd index is 89 for the $arrnum array. The value of the 1st index is Janifer for the $arrname array. The value of the 3rd index is 8.1 for the $arrmix array.
Example 2: Accessing Associative Array Without Loop
Create a PHP file with the following script that will create three associative arrays in three different ways and access the array values by defining the index. The first array has been created by defining the index and it contains all string values. The second array has been created by using [] brackets and it contains all string values. The third array has been created by using the array () function and it contains the number values. Next, the three values have been printed by defining the index.
//Create associative array using index
$arrassoc1["01267"] = "Md. Alam";
$arrassoc1["02875"] = "Mita Chowdhury";
//Create an associative array using [] brackets
$arrassoc2 = ["name" => "Mizanur Rahman", "email" => "[email protected]", "phone" => "018442341234"];
//Create an associative array using the array()
$arrassoc3 = array("Mizanur Rahman" => 80, "Mita Chowdhury" => 75, "Md. Alam" => 85);
//Print array values
echo "The value of the first array:". $arrassoc1["01267"]."<br />";
echo "The value of the second array:". $arrassoc2["name"]."<br />";
echo "The value of the third array:". $arrassoc3["Md. Alam"];
?>
Output
Open a browser and execute the above script from the server. The following output will appear after executing the script based on the index values. Three values of the particular index values have been printed in the output.
Example 3: Accessing Multi-dimensional Array Without Loop
Create a PHP file with the following script that will create a multi-dimensional associative array of four rows and four columns by using [] brackets; it will contain the string and number values. Next, the values of the 2nd row of the array will be printed by defining the index values.
//Create a multi-dimensional array of 4 rows and 4 columns
$foods = [
["id" => "001", "type" => "Pizza", "name" => "Chicken Pizza", "price" => 20],
["id" => "002", "type" => "Cake", "name" => "Mud Cake", "price" => 50],
["id" => "003", "type" => "Pasta", "name" => "Italian Pasta", "price" => 30],
["id" => "004", "type" => "Ice Cream", "name" => "Chocolate Icecream", "price" => 10]
];
//Print the values of second record of the array
echo "<b>The values of the 2nd row :</b><br />".
"ID :".$foods[1]["id"]."<br />".
"Type :".$foods[1]["type"]."<br />".
"Name :".$foods[1]["name"]."<br />".
"Price : $".$foods[1]["price"];
?>
Output
Open a browser and execute the above script from the server. The following output will appear after executing the script based on the index values:
Example 4: Count Array Values
The array values can be counted by using PHP built-in functions and by using the loop. Create a PHP file with the following script to know the way of counting the array values by using count() and sizeof() functions. Both functions work similarly and are able to count the elements of the multi-dimensional array recursively. Two arrays have been declared in the script. One is the numeric array of 5 string values and another is a two-dimensional array of 3 rows and 3 columns that contains string and number values. The first count() function has been used to count the total elements of the numeric array. The sizeof() function has been used to count the total number of rows of the two-dimensional array. The second count() function has been used to count the total elements of the two-dimensional array by using COUNT_RECURSIVE mode.
//Create one-dimensional array
$arrnames = ["Janifer","Jafar", "Jony", "jolly", "Jannat"];
//Create a two-dimensional array
$marks = [
["id" => "01145", "name" => "Kamal Hossain", "marks" => 80],
["id" => "01149", "name" => "Rina Rahman", "marks" => 89],
["id" => "01155", "name" => "Abir hasan", "marks" => 82]
];
//Print the total elements of the array
echo "The total elements of the one-dimensional array: ". count($arrnames)."<br />";
echo "The total number of rows of the two-dimensional array: ". sizeof($marks)."<br />";
echo "The total elements of the two-dimensional array : ". count($marks, COUNT_RECURSIVE);
?>
Output
Open a browser and execute the above script from the server. The following output will appear after executing the script. The numeric array contains 5 elements that have been printed. The two-dimensional array contains 3 rows and the two-dimensional array contains the total 3+(3×3) = 12 elements that have been printed.
Example 5: Accessing Array by Using ‘for’ Loop
In the previous examples, the particular array values are accessed without using any loop. It is efficient to use any loop to access all or most of the values of the array. Create a PHP file with the following script that uses the ‘for’ loop to access all values of a numeric array and an associative array. Here, the count() function has been used to count the total elements of the numeric array. The sizeof() function has been used to count the total rows of the two-dimensional associative array. The total number of elements has been used for the termination condition of the ‘for’ loop.
//Create one-dimensional array
$arrname = ["Janifer","Jafar", "Jony", "jolly", "Jannat"];
//Create a two-dimensional array
$marks = [
["id" => "01145", "name" => "Kamal Hossain", "marks" => 80],
["id" => "01149", "name" => "Rina Rahman", "marks" => 89],
["id" => "01155", "name" => "Abir hasan", "marks" => 82]
];
//print array values of the one-dimensional array
echo "The values of one-dimensional array using for loop:<br />";
for($i = 0; $i < count($arrname); $i++){
echo $arrname[$i], "<br />";
}
//print array values of the two-dimensional array
echo "<br />The values of two-dimensional array using for loop:<br />";
echo "ID Name Marks<br />";
for($i = 0; $i < sizeof($marks); $i++){
echo $marks[$i]["id"], " ";
echo $marks[$i]["name"], " ";
echo $marks[$i]["marks"], " ";
echo "<br />";
}
?>
Output
Open a browser and execute the above script from the server. The following output will appear after executing the script. Each value of the one-dimensional array has been printed in each line. Each row value of the two-dimensional array has been printed in each line.
Example 6: Accessing Array by Using ‘foreach’ Loop
Create a PHP file with the following script that uses ‘foreach’ loop to access all values of a numeric array and an associative array. Only the values will be printed for the numeric array and both keys and values will be printed for the associative array.
//Create a numeric array
$arrname = ["Janifer","Jafar", "Jony", "jolly", "Jannat"];
//Create an associative array
$client = ["id" => "01145", "name" => "Kamal Hossain", "email" => "[email protected]", "address" => "12, Dhanmondi, Dhaka."];
//print array values of the numeric array
echo "The values of a numeric array using a foreach loop:<br />";
foreach ($arrname as $value){
echo $value."<br />";
}
//print array values of the associative array
echo "<br />The values of associative array using foreach loop:<br />";
foreach ($client as $key => $value){
echo "$key => $value". "<br />";
}
?>
Output
Open a browser and execute the above script from the server. The following output will appear after executing the script. Each value of the numeric array has been printed in each line. Each key and value of the associative array has been printed in each line.
Example 7: Accessing the Array by Using the ‘while’ Loop
Create a PHP file with the following script that uses the ‘while’ loop to access all values of a numeric array. Here, the count() function has been used to count the total elements of the numeric array that has been used to define the termination condition of the loop. The counter variable has been used to iterate the ‘while’ loop until all values of the array are printed.
//Create a numeric array
$arrname = ["Janifer","Jafar", "Jony", "jolly", "Jannat"];
//Initialize the counter
$counter = 0;
echo "The values of the numeric array using while loop:<br />";
//Iterate the loop to print the values of the array
while ($counter < count($arrname))
{
echo $arrname[$counter] ."<br />";
$counter++;
}
?>
Output
Open a browser and execute the above script from the server. The following output will appear after executing the script. Each value of the numeric array has been printed in each line.
Example 8: Accessing Array by Using ‘do-while’ Loop
Create a PHP file with the following script that uses the ‘do-while’ loop to access all values of a numeric array. Here, the count() function has been used to count the total elements of the numeric array that has been used to define the termination condition of the loop. The counter variable has been used to iterate the ‘do-while’ loop until all values of the array are printed.
//Create a numeric array
$arrname = ["Janifer","Jafar", "Jony", "jolly", "Jannat"];
//Initialize the counter
$counter = 0;
echo "The values of the numeric array using do-while:<br />";
//Iterate the loop to print the values of the array
do {
echo $arrname[$counter]."<br />";
$counter++;
}
while ($counter < count($arrname));
?>
Output
Open a browser and execute the above script from the server. The following output will appear after executing the script. Each value of the numeric array has been printed in each line.
Example 9: Print Array by Using print_r() Function
The print_r() function is used to print the value of any variable. This function can be used by the coder to check the content of an array without using any loop for debugging purposes. Create a PHP file with the following script where the print_r() function has been used to print the content of a numeric array of 5 elements and the content of an associative array of 4 elements.
//Create a numeric array
$arrname = ["Janifer","Jafar", "Jony", "jolly", "Jannat"];
//Create an associative array
$client = ["id" => "01145", "name" => "Kamal Hossain", "email" => "[email protected]", "address" => "12, Dhanmondi, Dhaka."];
echo "The values of the numeric array by using print_r() function <br />";
print_r($arrname);
echo "<br /><br /> The values of the associative array by using print_r() function <br />";
print_r($client);
?>
Output
Open a browser and execute the above script from the server. The following output will appear after executing the script. The numeric key value has been shown with the value for the numeric array and the string key value has been shown with the value for the associative array.
Example 10: Print Array by Using var_dump() Function
The var_dump() function is another built-in function of PHP that prints the values of an array with the data type. This function can be used by the coder for debugging purposes. Create a PHP file with the following script where the var_dump() function has been used to print the content of a numeric array of 5 elements and the content of an associative array of 4 elements like the previous example. But the output of this function will be a little bit different from the print_r() function.
//Create a numeric array
$arrname = ["Janifer","Jafar", "Jony", "jolly", "Jannat"];
//Create an associative array
$client = ["id" => "01145", "name" => "Kamal Hossain", "email" => "[email protected]", "address" => "12, Dhanmondi, Dhaka."];
echo "The values of the numeric array by using var_dump() function: <br />";
var_dump($arrname);
echo "<br /><br /> The values of the associative array by using var_dump() function: <br />";
var_dump($client);
?>
Output
Open a browser and execute the above script from the server. The following output will appear after executing the script. According to the output, the numeric array contains 5 elements of string values and the type and the length of each value have been printed. The associative array contains 4 elements and the type and the length of each value have been printed.
Example 11: Sort Array Values by Using the sort() Function
The array values can be sorted by using any loop or by using any built-in PHP function. PHP has many built-in functions that sort the array values in different ways. The sort() function is one of them. It is a useful function of PHP to sort the array values in ascending order without using any loop. Create a PHP file with the following script where the sort() function has been used to sort three different types of arrays. A numeric array of all numbers, a numeric array of all strings, and an associative array of all strings have been defined in the script. The first sort() function will sort the array values in ascending order based on the numbers. The second sort() function will sort the array values in ascending order based on the characters of the string values. The third sort() function will sort the array values in ascending order based on the characters of the string values.
//Create a numeric array of numbers
$arrnum = [10,56,3,69,12,8];
//Create a numeric array of strings
$arrname = ["Janifer","Jafar", "Jony", "jolly", "Jannat"];
//Create an associative array
$client = ["id" => "01145", "name" => "Kamal Hossain", "email" => "[email protected]", "address" => "12, Dhanmondi, Dhaka."];
//Sort the number array
sort($arrnum);
echo "The sorted values of the numeric number array:<br />";
print_r($arrnum);
//Sort the string array
sort($arrname);
echo "<br /><br /> The sorted values of the numeric string array:<br />";
print_r($arrname);
//Sort the associative array
sort($client);
echo "<br /><br /> The sorted values of the associative array :<br />";
print_r($client);
?>
Output
Open a browser and execute the above script from the server. The following output will appear after executing the script. According to the output, the numbers of the first arrays have been sorted in ascending order and the string values of the second and third arrays have been sorted based on the characters.
Example 12: Reverse Array Values by Using array_reverse() Function
The array values can be printed from the last index to the first by using any loop or by using the array_reverse() function of PHP. It returns an array that contains the values of another array in reverse order. This function can be used to sort the values of an array in descending order. Create a PHP file with the following script where the array_reverse() function has been used to reverse the values of a numeric array and an associative array. The print_r() function has been used here to print the reversed values of the array.
//Create a numeric array
$arrnum = [10,56,3,69,12,8];
//Create an associative array
$client = ["id" => "01145", "name" => "Kamal Hossain", "email" => "[email protected]", "address" => "12, Dhanmondi, Dhaka."];
echo "The reversed values of the numeric array:<br />";
print_r(array_reverse($arrnum));
echo "<br /><br /> The reversed values of the associative array :<br />";
print_r(array_reverse($client));
?>
Output
Open a browser and execute the above script from the server. The following output will appear after executing the script. The last value of the numeric array was 8 which has been printed at the beginning of the first reversed array. The last key of the associative array was ‘address’ which has been printed at the beginning of the second reversed array.
Example 13: Search Value in the Array by Using array_search() Function
Sometimes it requires searching for a particular value in an array that can be done easily by using any loop. But PHP has a built-in function named array_search() to do this task. It returns true if the search value exists in the array, otherwise returns false. Create a PHP file with the following script that will take the search value from the URL parameter and use the array_search() function to check the value that exists in a numeric array of strings. If the search value exists, the message of the ‘if’ part will be printed; otherwise the message of the ‘else’ will be printed. If no search value is given in the URL, the “No search value is given.” message will be printed.
//Create a numeric array
$arrname = ["Janifer","Jafar", "Jony", "jolly", "Jannat"];
//Check whether the search value is set or not
if (isset($_GET['src']))
{
$search = $_GET['src'];
//Search the value in the array
if (array_search($search, $arrname))
echo "$search exists in the array.<br />";
else
echo "$search does not exist in the array.<br />";
}
else
echo "No search value is given.";
?>
Output
Open a browser and execute the above script from the server without any URL parameter. Here, the PHP file name is array13.php which is located under the PHP folder inside the root folder.
http://localhost/php/array13.php
The following output will appear if no parameter value is given in the URL:
Run the script again with the following parameter value:
http://localhost/php/array13.php?src=jony
Here, the parameter name is src and the parameter value is ‘jony’. The array contains a value, ‘Jony’ but not ‘jony’. The following output will appear after executing the above link:
Run the script again with the following parameter value:
http://localhost/php/array13.php?src=Jony
Here, the parameter name is src and the parameter value is ‘Jony’. The array contains a value, ‘Jony’. The following output will appear after executing the above link:
Example 14: Insert Value in the Array by Using array_unshift() Function
PHP has many built-in functions to insert data into an existing array. The array_unshift() function is one of them. One or more values can be inserted at the beginning of the array by using the function. PHP has another function named push() that inserts value at the end of the array. Create a PHP file with the following script that uses the array_unshift() function to insert one or more values into an array. A numeric array of 5 string values has been declared in the script. The array values have been printed by using a foreach loop before inserting any data. Next, the first array_unshift() function has been used to insert a new value in the beginning of the array. The second array_unshift() function has been used to insert two new values in the beginning of the array. The foreach loop has been used again to print the array values after adding three new values.
//Create a numeric array
$arrname = array("Janifer","Jafar", "Jony", "jolly", "Jannat");
//print the values of the array
echo "The values of array:<br />";
foreach ($arrname as $value){
echo $value."<br />";
}
//Insert a new value into the array
array_unshift($arrname, 'kamal');
//Insert two new values into the array
array_unshift($arrname, 'jamal', 'helal');
//print the values of the array again after inserting values
echo "<br /><br /> The values of array after insertion:<br />";
foreach ($arrname as $value){
echo $value."<br />";
}
?>
Output
Open a browser and execute the above script from the server. The following output will appear after executing the script. The original values of the array have been printed first that containing 5 elements. The modified values of the array have been printed later that contains 8 elements and all new values have been inserted at the beginning of the array.
Example 15: Remove Value From the Array by Using array_shift() Function
PHP has many built-in functions to delete data from an existing array. The array_shift() function is one of them. The value is removed from the beginning of the array by using this function. PHP has another function named pop() that deletes the value from the end of the array. Create a PHP file with the following script that uses the array_shift() function to delete the value from an array from the beginning. A numeric array of 5 string values has been declared in the script like the previous example. The array values have been printed by using a foreach loop before deleting any data. Next, the array_shift() function has been used to insert a new value at the beginning of the array. The foreach loop has been used again to print the array values after deleting a value.
//Create a numeric array
$arrname = array("Janifer","Jafar", "Jony", "jolly", "Jannat");
//print the values of the array
echo "The values of array:<br />";
foreach ($arrname as $value){
echo $value."<br />";
}
//Remove a value from the beginning of the array
array_shift($arrname);
//print the values of the array again after deleting a value
echo "<br /><br /> The values of array after deletion:<br />";
foreach ($arrname as $value){
echo $value."<br />";
}
?>
Output
Open a browser and execute the above script from the server. The following output will appear after executing the script. The original values of the array have been printed first that contains 5 elements. The modified values of the array will be printed later that contain 4 elements after deleting a value from the beginning of the array.
Conclusion
The array is a very useful data structure of PHP when it requires working with multiple data. The multiple values of different types can be stored into a single variable by using the array. The way of creating different arrays, accessing arrays, and modifying the content of the arrays have been described in this tutorial by using simple examples. PHP has many other built-in functions related to arrays that are not covered here.