Skip to main content

PHP Arrays

Body

An array is the same as variable except that it can store multiple values using an index key.

Here’s an example:

  1. <br />
  2. <?php<br />
  3. $names = array("John", "Peter", "Matthew", "Andrew")</p>
  4. <p>echo "The following are biblical name: " . names[0] . ", " . names[1] . ", " . names[2] . ", " . names[3] . ".";<br />
  5. ?><br />

You can also directly assign a value into an array with its index key, example:

  1. <br />
  2. <?php<br />
  3. $names[0] = "John";<br />
  4. $names[1] = "Peter";<br />
  5. $names[2] = "Matthew";<br />
  6. $names[3] = "Andrew";</p>
  7. <p>echo "The following are biblical name: " . names[0] . ", " . names[1] . ", " . names[2] . ", " . names[3] . ".";<br />
  8. ?><br />

The above example is using number as an index key. You can also use named key to identify an array easily.

Consider the following example:

  1. <br />
  2. <?php<br />
  3. $name["John"] = 35;<br />
  4. $name["Peter"] = 28;<br />
  5. $name["Matthew"] = 31;<br />
  6. $name["Andrew"] = 34;</p>
  7. <p>echo "John’s age is: " . $name["John"];<br />
  8. ?><br />

An associative array is very useful if you want to access your table’s record using a field name.

Example:

  1. <br />
  2. <?php<br />
  3. echo $table["name"];<br />
  4. echo $table["address"];<br />
  5. ?><br />

Add new comment