PHP Arrays Tutorial

28/12/2020
php
Before starting the tutorial, you should be clear on the concept of arrays. An array is one type of variable that can store a list of data. When you want to store a group of data in a single variable then you can use an array variable. Every value of the array can be read by the corresponding array index. Three types of array variables can be declared in PHP. These are numeric array, associative array and multidimensional array.

Numeric Array: The index of the array is number.
Associative Array: The index of the array is string.
Multidimensional Array: Array contains one or more arrays as elements.

In this tutorial, you will learn how you can declare and use arrays in your PHP script by using different examples.

Example-1: Numeric Array

You can declare numeric arrays in various ways, such as, defining an array structure, using array() method and assigning values. These declaration are shown in the following example. Open a text editor and creates a PHP file named numArray.php and add the following script to know how numeric arrays work. Here, a for loop is used to traverse each element of the array. You can use any of the three declarations to create a one dimensional numeric array in your script.

<?php
 
/*Define array using array structure */
$array1 = [‘Red’, ‘Green’, ‘Blue’];
echo ‘<br/>The values of array1: <br/>’;
foreach( $array1 as $value ) {
    echo "$value <br />";
}
 
/*Define array using array method */
$array2 = array(‘Rose’,‘Lily’,‘Sun Flower’,‘China Rose’);
echo ‘<br/>The values of array2: <br/>’;
foreach( $array2 as $value ) {
    echo "$value <br />";
}
 
/* Define array using index */
$array3[0] = "Mango";
$array3[1] = "Grape";
$array3[2] = "Banana";
$array3[3] = "Guava";
$array3[4] = "Orange";
echo ‘<br/>The values of array3: <br/>’;
foreach($array3 as $value ) {
     echo "$value <br />";
}
?>

Now, open the browser and browse the location to run the script.

http://localhost/phpcode/numArray.php

You will get the following output if the script executed properly.

Example-2: Associative array

The declaration of an associated array is similar to a numeric array. You can declare a numeric array without defining the index but you can’t declare an associative array without defining an index. You have to define key-value pairs properly at the time of associative array declaration and the key or index value must be a string. Create a php file named assocArray.php and add the following code to show the use of associative arrays. Two ways of associative array declarations are shown in the following script. array()  method is used first to declare an associative array and for loop is used to read key-value pair. The second associative array is declared by assigning values and array values are read and printed separately.

<?php
 
/* Associate array declaration using array() method */
$Books = array("Beginning PHP and MySQL" => 100, "Learning JQuery" => 60,
"Laravel 5.5" => 150,"AngularJS" => 160);
 
foreach( $Books as $key=>$value ) {
    echo  "The price of <b> $key </b> is <b> $value </b><br />";
}
 
/* Associate array declaration by assigning values */
$Person[‘John’] = "White";
$Person[‘Peter’] = "Yellow";
$Person[‘Ella’] = "pink";
$Person[‘Fahmida’] = "Blue";
$Person[‘Mick’] = "Red";
 
echo "<br/>The favorite color of <b> John </b> is: <b>". $Person[‘John’] . "</b><br />";
echo "The favorite color of <b> Peter </b> is: <b>". $Person[‘Peter’]. "</b><br />";
echo "The favorite color of <b> Fahmida </b> is: <b>". $Person[‘Fahmida’]. "<b><br />";
 
?>

Now, open the browser and run the script.

http://localhost/phpcode/assocArray.php

You will get the following output if the script is executed properly.

Example-3: Multidimensional Array

One or more arrays can be used as array elements of the multidimensional array and array elements can also contain another array(s) as elements. You can use multiple indexes or for loops to access the values of a multidimensional array. How you create and use multidimensional arrays in PHP are shown in the following example. Create a new PHP file named mutiArray.php and add the following script.  Array values of two dimensional arrays, $employees are read by using multiple for loops and multiple  indexes. You have to use two for loops to read the values. Here, the first loop is used to read the main array and the second loop is used to read the values of the internal array. If you want to access the values of multidimensional array without using a for loop then you can access the values by using multiple indexes which is shown in the last part of the script.

<?php
 
/*Multidimentional array declaration using array() method*/
$employees = array(
"Jonny" => array("post" => "Sales Executive","email" =>"[email protected]",
"phone" => "953456788"),
"Mac" => array("post" => "Manager","email" =>"[email protected]",
"phone" => "900267748"),
"Gilmore" => array("post" => "Director","email" =>"[email protected]",
"phone" => "988777789"),
);
 
/*Reading multidimensional array using for loop */
foreach( $employees as $key=>$value ) {
    echo "<br/>";
    echo  "Employee Name:<b> $key </b><br/>";
    foreach( $value as $k=>$v ) {
        echo "$k: <b> $v </b><br/>";
    }
}
 
echo "<br/>";
 
/* Reading multi-dimensional array multiple indexes */
echo "The email address of <b> Jonny </b> is : " ;
echo $employees[‘Jonny’][’email’] . "<br />";
 
echo "The phone number of <b> Mac </b> is : ";
echo $employees[‘Mac’][‘phone’] . "<br />";
 
echo "The designation of <b> Gilmore </b> is : " ;
echo $employees[‘Gilmore’][‘post’] . "<br />";
?>

Run the script from the browser.

http://localhost/phpcode/multiArray.php

You will get the following output if the script is written properly.

You will need to use different arrays in your scripts to solve various programming problems. By practicing the above examples, you can understand properly how you can use array variables in php.

ONET IDC thành lập vào năm 2012, là công ty chuyên nghiệp tại Việt Nam trong lĩnh vực cung cấp dịch vụ Hosting, VPS, máy chủ vật lý, dịch vụ Firewall Anti DDoS, SSL… Với 10 năm xây dựng và phát triển, ứng dụng nhiều công nghệ hiện đại, ONET IDC đã giúp hàng ngàn khách hàng tin tưởng lựa chọn, mang lại sự ổn định tuyệt đối cho website của khách hàng để thúc đẩy việc kinh doanh đạt được hiệu quả và thành công.
Bài viết liên quan

How to Print Arrays in PHP

Array variables are used to store multiple values in a single variable.  Sometimes it is required to check the structure...
29/12/2020

How to Parse JSON in PHP

The full form of JSON is JavaScript Object Notation. It is a text-based format of data like XML which is very easy to write...
28/12/2020

How to Apply Try Catch Block in PHP

Exception handling is a very important feature of any object-oriented programming. When any logical or system error arrives...
29/12/2020
Bài Viết

Bài Viết Mới Cập Nhật

Mua proxy v4 chạy socks5 để chơi game an toàn, tốc độ cao ở đâu?
18/05/2024

Thuê mua proxy Telegram trọn gói, tốc độ cao, giá siêu hời
18/05/2024

Thuê mua proxy Viettel ở đâu uy tín, chất lượng và giá tốt? 
14/05/2024

Dịch vụ thuê mua proxy US UK uy tín, chất lượng số #1
13/05/2024

Thuê mua proxy Việt Nam: Báo giá & các thông tin MỚI NHẤT
13/05/2024