PHP - Accessing Array Elements

Introduction

Consider the following code

Demo

$authors = array("A","B","C","D");
$myAuthor = $authors[0];      // $myAuthor contains"A"
echo $myAuthor;/*from w w w .  ja v a 2s  . c  o m*/
$anotherAuthor = $authors[1]; // $anotherAuthor contains"B"
echo $anotherAuthor;

Result

To access the elements of an associative array, simply use string indices rather than numbers:

$myBook = array("title"=> "Java",
                "author"=> "John A",
                "pubYear"=>  2018);

$myTitle = $myBook["title"];    // $myTitle contains"Java"
$myAuthor = $myBook["author"];  // $myAuthor contains"A"

You don't have to use literal values within the square brackets; you can use any expression, as long as it evaluates to an integer or string as appropriate:

Demo

<?php
$authors = array("A","B","C","D");
$pos = 2;/*  w  ww .  j a  v a 2 s  .c o  m*/
echo $authors[$pos + 1]; // Displays"D"
?>

Result

Related Topic