PHP Access Array Element

In this chapter you will learn:

  1. How to access array element
  2. Syntax to access array element
  3. Example - Access indexed array elements
  4. Example - Access elements from associative arrays
  5. Example - Put expression into array operator[]

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/*from  j  av a  2 s  . 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/*from  j  a v a2s  .  com*/
$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/*from   j a va  2s .  c om*/
$authors = array( "Java", "PHP", "CSS", "HTML" ); 
$pos = 2; 
echo $authors[$pos + 1]; // Displays "HTML"   
?>

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. How to change an element in an array
  2. Syntax to change array element
  3. Example - Change array element by index
  4. Example - Add to the last element
  5. Example - Append to the array end
Home » PHP Tutorial » PHP Array
PHP Array
PHP Create Indexed Array
PHP Create Associative Arrays
PHP Array Operator
PHP Access Array Element
PHP Change Array Element
PHP Create Array using Square Bracket
PHP Array Element Loop Through
PHP Array foreach loop
PHP Change Array Values with foreach
PHP Array Multidimensional
PHP Access Element in Multidimensional Array
PHP Loop Through Multidimensional Array