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. <?php
  2. $names = array("John", "Peter", "Matthew", "Andrew")
  3.  
  4. echo "The following are biblical name: " . names[0] . ", " . names[1] . ", " . names[2] . ", " . names[3] . ".";
  5. ?>
You can also directly assign a value into an array with its index key, example:
  1. <?php
  2. $names[0] = "John";
  3. $names[1] = "Peter";
  4. $names[2] = "Matthew";
  5. $names[3] = "Andrew";
  6.  
  7. echo "The following are biblical name: " . names[0] . ", " . names[1] . ", " . names[2] . ", " . names[3] . ".";
  8. ?>
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. <?php
  2. $name["John"] = 35;
  3. $name["Peter"] = 28;
  4. $name["Matthew"] = 31;
  5. $name["Andrew"] = 34;
  6.  
  7. echo "John’s age is: " . $name["John"];
  8. ?>
An associative array is very useful if you want to access your table’s record using a field name. Example:
  1. <?php
  2. echo $table["name"];
  3. echo $table["address"];
  4. ?>

Add new comment