Tuesday, 31 January 2017

ARRAYS IN PHP

Array is a collection of heterogeneous elements. PHP is loosely typed language, hence in this way we can store any type of value in array. Array is a collection of elements, where each element is a combination of key and value. By default, first element key starts with key 0. Difference between a variable and array is variable can store single value whereas an array can store collection of values. By using print_r function we can print all elements of array.

Example –
<?php
$num=array(10,20,30);
print_r($num); // print all elements of array
echo $num[1]; // prints only one element with key 1
?>

Output –
Array
(
    [0] => 10
    [1] => 20
    [2] => 30
)
20

Example –
<?php
$num=array(5,100=>10,20,50=>30,'scott');
print_r($num);
?>

Output –
Array
(
    [0] => 5
    [100] => 10
    [101] => 20
    [50] => 30
    [102] => scott // because of the highest previous address
)

Example –
<?php
$num=array(10,20,0=>30); // overrides 10 with 30
print_r($num);
?>

Output –
Array
(
    [0] => 30
    [1] => 20
)

Example –
<?php
$arr=array();
$arr[0]=10;
$arr[1]=20;
$arr[2]=30;
print_r($arr);
?>

Output –
Array
(
    [0] => 10
    [1] => 20
    [2] => 30
)


Array elements are of two types –

1. Numeric elements – Elements with number key comes under numeric elements.

2. Associative elements – Elements with string key comes under associative array.

Example –
<?php
$arr=array();
$arr[0]=10;
$arr['hr']="Scott";
$arr['admin']="John";
print_r($arr);
?>

Output –
Array
(
    [0] => 10
    [hr] => Scott
    [admin] => John
)

No comments:

Post a Comment