What are the Arrays in PHP
An array is a collection of values in a single variable name.The variables in an array is called the array elements.Array elements are accessed using a single name and an indexed number represending the postion of the elements with in the array.The lenght of an array will be less than the actual length.Since index is starts with zero.We can insert the values for each elemnets in an array by using a subscript as follows,
<?php
$a [0] = "apple";
$a [1] = "cherry";
$a [2] = "plum";
?>
$a [0] = "apple";
$a [1] = "cherry";
$a [2] = "plum";
?>
We can also use array() function to declare an array of predifined values
<?php
$a = array("apple","cherry","plum");
?>
$a = array("apple","cherry","plum");
?>
Values taken from the array is similar to assign values to the array.
<?php
$abc = $a[2];
?>
Now the value of the variable $abc will be "plum" , Loops are widely used to manipulate the arrays.The following code is used for assigning and printing the values in an array.
<?php
for($i=1;$i<=10;$i++) { $arr [$i] = $i*$i; echo $arr [$i]; }
?>
There are three types of arrays in php:-
<?php
$abc = $a[2];
?>
Now the value of the variable $abc will be "plum" , Loops are widely used to manipulate the arrays.The following code is used for assigning and printing the values in an array.
<?php
for($i=1;$i<=10;$i++) { $arr [$i] = $i*$i; echo $arr [$i]; }
?>
There are three types of arrays in php:-
- Numeric(Indexed) array - An array with a numeric index
- Associative array - An array where each ID key is associated with a value
- Multidimensional array - An array containing one or more arrays
Numeric Array
Numeric or Indexed array has numeric keys that start with zero.Any kind of values can be assigned in the elements of the array.The following code shows how to assigning values to an indexed array.<?php
$a = array("apple","cherry","plum");
?>
Or
<?php
$a [0] = "apple";
$a [1] = "cherry";
$a [2] = "plum";
?>
Associative Array
In associative array we can use user defined keys (named keys) for assigning values to the array.The usage of associative array is given below.<?php
$a["apple"]="Rs.72";
$a["grape"]="Rs.152";
$a["cherry"]="Rs.350";
?>
Multidimensional Array
A multidimensional array is an array that contains at least one other array as the value of one of the indexes.
<?php
$MDA= array(
"A" => array(0 => "red", 2 => "blue", 3 => "green"),
"B" => array(1 => "orange", 2 => "black"),
"C" => array(0 => "white", 4 => "purple", 8 => "grey")
);
echo $MDA["A"][3]; // green
echo "<br>";
echo $MDA["C"][8]; // grey
?>
$MDA= array(
"A" => array(0 => "red", 2 => "blue", 3 => "green"),
"B" => array(1 => "orange", 2 => "black"),
"C" => array(0 => "white", 4 => "purple", 8 => "grey")
);
echo $MDA["A"][3]; // green
echo "<br>";
echo $MDA["C"][8]; // grey
?>
Arrays in PHP by NiPS Institute Best Coaching Institute in New Delhi
No comments:
Post a Comment