Thursday 1 April 2021

Php: Arrays

Arrays are used to store collection of values. Values can be of any type.

 

How to define an array?

Arrays can be created either using index notation or using array() function.

 

Example

$arr1 = [2, 3, 'Hello', true];

$arr2 = array(2, 3, 'Hello', true);

 

Different types of arrays

There are two types of arrays.

a.   Indexed arrays: Use numbers as keys

Ex: $arr1 = [2, 3, 'Hello', true];

 

b.   Associative array: Use strings as keys

Ex:

$arr1 = [

"id" => 1,

"age" => 32,

 "name" => "Sailu",

 "male" => false

];

 

arrays_demo.php

#!/usr/bin/php

<?php
    
   $arr1 = [2, 3, 'Hello', true];
   
   $arr2 = array(2, 3, 'Hello', true);
   
   echo "Contents of arr1 are : \n";
   print_r($arr1);
   
   echo "\nContents of arr2 are : \n";
   print_r($arr2);
   
?>

 

Output

$./arrays_demo.php 

Contents of arr1 are : 
Array
(
    [0] => 2
    [1] => 3
    [2] => Hello
    [3] => 1
)

Contents of arr2 are : 
Array
(
    [0] => 2
    [1] => 3
    [2] => Hello
    [3] => 1
)

 

Analyze output

Array

(

    [0] => 2

    [1] => 3

    [2] => Hello

    [3] => 1

)

 

 

From the output, you can confirm

a.   Variable is of type Array

b.   Elements in array are counted from index 0. First element is stored at index 0, 2nd element is at index 1 etc.,

 

You can access the elements of array using index. For example, arr1[0] return the value at index 0.

 

array_access_elements_demo.php

#!/usr/bin/php

<?php
$arr1 = [
    2,
    3,
    'Hello',
    true
];

echo "arr1[0] = $arr1[0]\n";
echo "arr1[1] = $arr1[1]\n";
echo "arr1[2] = $arr1[2]\n";
echo "arr1[3] = $arr1[3]\n";
?>

 

Output

$./array_access_elements_demo.php 

arr1[0] = 2
arr1[1] = 3
arr1[2] = Hello
arr1[3] = 1

 

Associative arrays

Unlike other programming languages, arrays in php can act as key->value pairs.

 

Example

$arr1 = [

"id" => 1,

"age" => 32,

 "name" => "Sailu",

 "male" => false

];

 

 

array_named_index.php

#!/usr/bin/php

<?php
$arr1 = [
    "id" => 1,
    "age" => 32,
    "name" => "Sailu",
    "male" => false
];

echo "Contents of arr1 are : \n";
print_r($arr1);

?>

 

Output

$./array_named_index.php 

Contents of arr1 are : 
Array
(
    [id] => 1
    [age] => 32
    [name] => Sailu
    [male] => 
)

 

 

 

 

 

 

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment