PHP Access Array Element

Description

By using array operator [] we can access elements in an array.

Syntax

For indexed array we can use number index to access array element


$arrayName[0]
$arrayName[1]

For associative arrays we can put element name to the array operator[]


$arrayName["key1"]
$arrayName["key2"]

Example 1

Access indexed array elements


<?PHP// ww w .jav  a  2s  .c o  m
$authors = array( "Java", "PHP", "CSS", "HTML" ); 
$myAuthor = $authors[0];      // $myAuthor contains "Java" 
$anotherAuthor = $authors[1]; // $anotherAuthor contains "PHP" 
print($myAuthor);
print($anotherAuthor);
?>

The code above generates the following result.

Example 2

Access elements from associative arrays


<?PHP/*ww  w . ja v a 2s  .co m*/
$myBook = array( "title" =>  "Learn PHP from java2s.com", 
                 "author" =>  "java2s.com", 
                 "pubYear" =>  2000 ); 

$myTitle = $myBook["title"];    // $myTitle contains "Learn PHP from java2s.com" 
$myAuthor = $myBook["author"];  // $myAuthor contains "Java"   
print($myTitle);
print($myAuthor);
?>

The code above generates the following result.

Example 3

We 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.


<?PHP//w w  w.  j  ava2  s. c o m
$authors = array( "Java", "PHP", "CSS", "HTML" ); 
$pos = 2; 
echo $authors[$pos + 1]; // Displays "HTML"   
?>

The code above generates the following result.





















Home »
  PHP Tutorial »
    Data Types »




Array
Array Associative
Array Util
ArrayObject
Data Types
Date
Date Format
DateTime
Number
String
String Escape
String Filter
String HTML
String Type
Timezone