Arrays in PHP - How to create an Array in PHP - Types of array in PHP


Arrays in PHP - How to create an Array in PHP - Types of array in PHP
Arrays are the special variables in PHP which can store more then one value into a single variable. In PHP a array() function is used to create an array.The PHP array can store any kind of value into it and combination of different type of values into the array variable.

Example for creating an array in PHP:-

<?php

$colors=array("red","green","blue","white","black");
?>

Example for printing an array in PHP:-


<?php

$colors=array("red","green","blue","white","black");
echo $colors[0].",".$colors[1].",".$colors[2].",".$colors[3].",".$colors[4];

?>

There are three types of array in PHP:-


  • indexed array.
  • associative array.
  • multidimensional array. 
Indexed array :- arrays with numeric index or you can say these type of arrays are similar to the c, java's array.

>>two way to creating the indexed arrays in PHP

<?php
$colors=array("red","green","blue");
?>

<?php
$colors[0]="red";
$colors[1]="green";
$colors[2]="blue";
?>

Associative array :- arrays with a key which is associative with each  value.

>>two way to creating the associative arrays in PHP

<?php
$colors=array("1"=>"red","2"=>"green","3"=>"blue");
?>

<?php
$colors['1']="red";
$colors['2']="green";
$colors['3']="blue";
?>

printing an associative array:

<?php
$colors=array("1"=>"red","2"=>"green","3"=>"blue");
echo $colors['1'].",".$colors['2'].",".$colors['3'];
?>

Multidimensional array :- An array which can contain another array as a value is called multidimensional array. we can create two or three dimensional array as well.

Constructing multi-dimensional array:-

<?php
$colors=array
(
array("1"=>"red","2"=>"white");
array("3"=>"green","4"=>"blue");
);
?>






{ 0 comments... read them below or add one }

Post a Comment