Using Strings for Indexes

As mentioned earlier in this chapter, you can use strings as indexes into your arrays. The global variable _SESSION in PHP uses strings as its indexes. The syntax for accessing an array that uses strings as an index looks like this:

_SESSION[“gTurn”];

Creating an array that uses strings for an index is very simple. Recall the first example I used to initialize an array with elements in a specific index.

$board[0] = “A”:
$board[1] = “B”:
$board[5] = “C”:
$board[7] = “D”:

Instead of using an integer as an index you would simply replace it with a string, as the following example demonstrates:

$board[“element1“] = “A”:
$board[“element2“] = “B”:
$board[“element3“] = “C”:
$board[“element4“] = “D”:

You can also use the => operator along with the array() function to create an array with strings as indexes.

$board = array(“element1” => “A”, “element2” => “B”,
    “element3” => “C“, “element4” => “D”);

If you use strings as indexes into your array, you have to access the array with the specified string indexes. In other words, if you typed in the following code:

<?php
$board = array(“element1” => “A”, “element2” => “B”,
    “element3” => “C”, “element4” => “D”);
echo($board[“element1”]);
echo($board[0]);
?>

You would get an error when the PHP interpreter tried to print the last line, echo($board[0]”), that looks like Figure 6.2.

Figure 6.2. Trying to access a string-indexed array with an integer.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset