php

PHP Accesing Array


 

Arrays can be accessed using square brackets. PHP arrays can be either numerically indexed or associative (using strings as keys) which we have already cover.

 

1.  Indexed Array:
 

Example :

<?php
    $myArray = array(1, 2, 3, 4, 5);

    // Accessing the third element (index 3)
    echo $myArray[3]; // Output: 4
?>

In this example, $myArray[3] retrieves the value at index 3 in the array $myArray, which is the fourth element because array indices start at 0.

 

2. Associative Array:
 

Example :

<?php
    // Associative array
    $myAssocArray = [
        "first" => 1,
        "second" => 2,
        "third" => 3,
        "fourth" => 4,
        "fifth" => 5
    ];

    // Accessing the element with key "third"
    echo $myAssocArray["third"];  // Output: 3
?>

In this example, $myArray[3] retrieves the value at index 3 in the array $myArray, which is the fourth element because array indices start at 0.

 

Note: PHP arrays can be dynamic and hold a mix of data types. Numerical indices start at 0, while associative array keys can be strings or integers.