Array in PHP

Array in PHP

Array in PHP-

In PHP, there are three types of arrays , and array()  function is used to create an array in PHP.

1- Indexed or Numeric Array-

In a numeric or an indexed array elements of an array are indexed with numeric values.
For example, if you define an array ar with the elements 15, 25, 35, 45, 55, 65, 75, 85.
i.e.
<?php
$ar=array(15, 25, 35, 45, 55, 65, 75, 85);
?>
Then you will access 15 using index 0.
i.e
echo “This is the value “, $ar[0], ” at index 0 “;
echo “\n”;

The same way you can also access other elements, see below.

Array in PHP

 

2- Associative Array-

In an associative array, instead of numeric index you can use index of your own choice.

For example, see the defined array ar
<?php
$ar=array(“a”=>15, “b”=>25, “c”=>35, “d”=>45, “e”=>55, “f”=>65, “g”=>75, “h”=>85);
?>
In the above PHP code an array ar is defined in which you can observe the difference from numeric array. In associative array you can see user defined indices or keys a, b, c, d, e, f, g, h instead of indices 0, 1, 2, 3, 4,…….etc.

Then you will access 15 using index “a”.
i.e
echo “This is the value “, $ar[“a”], ” at index a”;
echo “\n”;

 

Array In PHP

 

3- Multidimension Array-

 

In multidimensional array, an element can also be an array.

For example, I am going to create a two dimensional array

<?php
$ar=array(“a”=>array(“apple”,”ant”),”b”=>array(“bananas”,”baby”));
?>
In the above code you can see two dimensional array i.e. array within array and you can access elements of ar array in the following way.
“apple” can be accessed using echo $ar[“a”][0] statement
i.e echo $ar[“a”][0]
“ant” can be accessed using echo $ar[“a”][1] statement
echo $ar[“a”][1]

“bananas” can be accessed using echo $ar[“b”][0] statement
i.e. echo $ar[“b”][0]
“baby” can be accessed using echo $ar[“b”][0] statement
i.e. echo $ar[“b”][1]
See the program and output below,

Array In PHP

 

 

 

Leave a Comment

Your email address will not be published. Required fields are marked *

©Postnetwork-All rights reserved.