PHP: Arrays

Back to more PHP, you may be wondering how PHP stores information. It can call or modify information in an SQL database, but we'll cover that later. So far, we know that we can save individual bits of information as variables. Let's look at Arrays. An Array is a list, and it allows you to save more than one bit of information within a single variable.

Array Syntax

A very simple array, could simply be a shopping list, like the example below.

<?php
      $SampleArray = array("Egg", "Tomato", "Beans");
    ?>  

An array starts with a variable, and then is followed by the =, just like we've done before. However, the array() portion of the statement is where we can put in multiple values. These could be strings, numbers, and/or previously declared variables. The information within the ellipses are separated by commas and each string is within double quotes, just like we've seen with past variable declarations or echo statements.
Array Offsets

Let's say, we had an array with different numbers and we wanted to echo the third number within the array. Each item in an array is numbered starting from 0, from left to right, like you were reading a book. In order to echo the third number in the array, we'd use an offset. Offsets allow us to pull a specific item from an array. An example would look something like

<?php
        $tens = array(10, 20, 30, 40, 50);
        echo $tens{2}
      ?>

Modifying Arrays

In order to modify an entry in an array, we start declaring our array, and then using an array offset statement to change the item in the offset to a different value. For example, I've got an array that contains a list of string values representing various programming languages. The third language listed in the array is "Python" but I want to change it to Pythoon for whatever reason. The code to do that would look like

<?php
        $languages = array("HTML/CSS",
        "JavaScript", "PHP", "Python", "Ruby");
       
        $languages[2] = "Pythoon";
       
        echo $languages[2];
       
      ?>

You can use the same idea to delete an entry from an array. Using the same array, I can use the unset command to remove a specific entry from the array.

<?php
        $languages = array("HTML/CSS",
        "JavaScript", "PHP", "Python", "Ruby");      
       
        unset($languages[3]);
       
        foreach($languages as $lang) {
          print "<p>$lang</p>";
        }
      ?>

Comments

Popular posts from this blog

Installing CentOS 7 on a Raspberry Pi 3

Modifying the Zebra F-701 & F-402 pens

How to fix DPM Auto-Protection failures of SQL servers