PHP Access Array Element
In this chapter you will learn:
- How to access array element
- Syntax to access array element
- Example - Access indexed array elements
- Example - Access elements from associative arrays
- 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:
- How to change an element in an array
- Syntax to change array element
- Example - Change array element by index
- Example - Add to the last element
- Example - Append to the array end
Home » PHP Tutorial » PHP Array