Complete PHP Tutorial – Chapter 6

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

Credit Goes to Mr. RYDIOO

You may also like:

Sarcastic Writer

Step by step hacking tutorials about wireless cracking, kali linux, metasploit, ethical hacking, seo tips and tricks, malware analysis and scanning.

Related Posts