
In this tutorial, we’ll cover Arrays and its types which are Numeric Arrays, Multi-Dimensional Arrays and Associative Arrays.
Numeric Arrays
An array is a special type of variable that is capable of storing multiple values. Numeric arrays give a numeric index to all of the values within the array. The first index of an array is always 0 and there are two ways to define them:
PHP Code:
<?php
$myfirstarray = array(
item1 => “value1”,
item2 => “value2”,
item3 => “value3”,
)//OR
$array = array(“value1”, “value2”, “value3”);
// You can also assign the index manually like this.
?>
We access an element by referencing its
PHP Code:
<?php
echo $dogs[1]; // Will echo Lola.
?>
Associative Arrays
Associative arrays are similar to numeric arrays. However, the values in the array are given named keys that you assign to them. There are two ways to create an associative arrays:
PHP Code:
<?php
$characters = array(“Yeah”=>”19″,”Hub”=>”110″,”Website”=>”18”);
//or
$characters[‘Yeah’] = “19”;
$characters[‘Hub’] = “110”;
$characters[‘Website’] = “18”;
// both give the same result
?>
To access the values of this kind of array, you use the named keys instead of the usual numeric value.
PHP Code:
<?php
echo $characters[‘man’];
?>
Multi-Dimensional Arrays
A multi-dimensional array is an array that contains one or more arrays. The dimension indicates the amount of indices you would need to select an element within in.
For a two dimensional array you would need two indices to access it and for a three dimensional one you would need 3 and so on. Arrays more than 3 layers deep are very difficult to handle so I would suggest staying away from them. The arrays inside of the multi-dimensional arrays can be either numeric or associative. Let’s create a two dimensional array:
PHP Code:
<?php
$people = array(
‘friends’=>array(‘Name1′,’Gaurav’)
‘enemies’=>array(‘Name2′,’Aman’)
‘family’=>array(‘Name3′,’Pappu’)
);
?>
This two dimensional array has 3 arrays and two indices. We can think of these as a row and columns. To access this array we need to specify both the indices.
PHP Code:
<?php
echo $people[‘friends’][0];
echo $people[‘family’][1];
?>
Continue to Next Chapter – Complete PHP Tutorial – Chapter 7
You may also like:- The Intricate Process of Designing and Developing Online Casino Slot Games
- Bella Protocol vs. Traditional Banking: A New Era of Financial Services
- How Does Spam Score Affect SEO?
- Top Email Marketing Applications for Effective Campaigns
- Edit and Compile Code with the Best 5 Code Editors
- 50+ Top DevSecOps Tools You Need To Know
- Learn How to Add Proxy and Multiple Accounts in MoreLogin
- Can Jews and Evangelical Christians Co-Exist?
- What Will Be Digital Information Technology in 2023
- Advantages Of Using Opkey SAP Testing Services