Broad Network


PHP Array Basics with Security Concerns

Basics of PHP with Security Considerations – Part 10

Foreword: In this tutorial I explain the PHP Array basics.

By: Chrysanthus Date Published: 18 Jan 2018

Introduction

This is part 10 of series, Basics of PHP with Security Considerations. In PHP an array is a variable to which a list of values is assigned to. Each value (item) can be a literal or a variable representing a literal. In this tutorial I explain the PHP Array basics. You should have read the previous parts of the series before reaching here, as this is the continuation.

List Examples
Imagine that you are a proprietor of a small company, and you have 10 employees. In your PHP program, you can have their first names in an array, where each list item is a first name. Let the list be: John, Mary, Peter, Augustine, Angela, Susan, Martin, Grace, Paul, Simon.

Another example of list occurs when you are dealing with code names. In a table of business data, code names called IDs often identify the rows in a table. You have code names in other situations in life. In a list of code names, some code names may be letters, others may be a mixture of letters and numbers and yet others may just be numbers. An example of such a list is: HBWE, FGTR, HTNK, 4587, 4526, 4053, AB12, GB58, TG45, RE69.

As another example of array items, you can have a list that is just made up of numbers. An example is: 10, 20, 30, 40, 50, 60, 70, 80, 90, 100. The aim in this tutorial is just to know how to make a list into an array and then manipulate the array.

A list does not need to have only 10 items. A list can have, 0, 1, 2, 3 or more items. I will use any of the above lists to explain the meaning of array and how to manipulate an array.

Creating an Array
You create an array by putting the list items in parentheses; separate the items with commas, precede the parentheses with the reserved word, array, and then assign the construct to a variable. The second list above is made into an array as follows:

$arr = array("HBWE", "FGTR", "HTNK", 4587, 4526, 4053, "AB12", "GB58", "TG45", "RE69");

Note the following in the above array: Each letter-only item is in quotes; each number-only item is not in quotes. Each item consisting of letters and numbers is in quotes.

In the above statement, arr is a name of your choice for the array, but it has to be preceded by $.

Sometimes, in programming, you might have to create an array before you know what items will form its list. In that case, the list can be empty when creating the array as in the following statement:

$arr = array();

When the list is empty, you may not have to type empty brackets without items as just done; you may type:

$arr;

This last statement has a weakness: it is not clear whether the variable will hold a string or an int or a float or a Bool or a NULL or even an array.

Populating an Array
An empty array created is said to have no population because it has no items. You can populate (add items) to an empty array. First, know that the syntax to change the content of an array cell (element) or give it a new value is:

      $arrayName[i] = value;

A string is text in quotes. If the value is a string, it is in quotes (single or double). If the value is a number, it does not have to be in quotes. If the value is a mixture of letters and numbers, it should be in quotes (single or double). The array name is followed by square brackets. Inside the square brackets you have a number. This number is the position of the value (item) in the array. This position number is called the index. Index counting in computing, begins from zero, not 1. So the first element (item) in an array is at index 0, the second at index, 1, the third at index 2, and so on. The following code will create an empty array and populate it:

$rrr;

$rrr[0] = "HBWE";
$rrr[1] = "FGTR";
$rrr[2] = "HTNK";
$rrr[3] = 4587;
$rrr[4] = 4526;
$rrr[5] = 4053;
$rrr[6] = "AB12";
$rrr[7] = "GB58";
$rrr[8] = "TG45";
$rrr[9] = "RE69";

There are 10 elements in the array, with indices from zero to 9 as required. Note that to identify each array element, we use the array name and begin ir with $.

Accessing an Element in an Array
Accessing an element means to get at the value of the element of the array. The syntax is:

    $arrayName[i]

You can access an element to read the value or change the value.

Reading the value of an Array Element
The above expression returns the value of an element. The following code reads and displays the value of array element number 5, which has the index, 4:

<?php

    $rrr;

    $rrr[0] = "HBWE";
    $rrr[1] = "FGTR";
    $rrr[2] = "HTNK";
    $rrr[3] = 4587;
    $rrr[4] = 4526;
    $rrr[5] = 4053;
    $rrr[6] = "AB12";
    $rrr[7] = "GB58";
    $rrr[8] = "TG45";
    $rrr[9] = "RE69";

    $var =  $rrr[4];
    echo $var;

?>

The code begins with the declaration of an empty array. The next 10 statements populate the array. The last-but-one statement is:

    $var =  $rrr[4];

Here, a new variable ($var), which will hold a simple single value is declared. At the same time, the fifth elements value is read and assigned to the variable. Fifth element means index 4. The last statement sends the value of the variable, $var to the browser. The value of the variable, $var is the value of $rrr[4].

Try the above code. Remember, to try a code sample, you should copy and past it in a text editor (or re-type it in a text editor). Save the file in the home directory (replace the content of temp.php). Execute the file at the browser by typing the URL of the file at the address bar of your browser; and then click Go. If you tried the above code, you should see the number 4526 at the browser.

Changing the value of an Array Element
Before I continue, remember that you can also create an array while populating it at the same time, as in the following code.

The value of the third element (index 2) is changed to “yes”:

<?php

    $arr = array("HBWE", "FGTR", "HTNK", 4587, 4526, 4053, "AB12", "GB58", "TG45", "RE69");

    $arr[2] = "yes";

    echo $arr[2];

?>

The first statement creates and populates the array automatically in list format. The last-but-one statement changes the value of the third element from "HTNK" to "yes". You do this by just assigning the new value to the variable of the third array element. The last statement sends the value of the third element to the browser. You do not necessarily have to assign the value of an array element to a new variable, as done in the previous code in order to use (print) it. You can use (echo) it directly, as done in this code.

The Length of an Array
The length of an array is the number of elements in the array. The length of all the above arrays is 10. However, the highest index of the arrays is 9. To determine the length of an array, you have to use the count function, whose simplified syntax is:

        int count ($var)

The count function returns an integer (whole number); that is why you have int at the beginning of the syntax. The argument, $var to the count function call is the array.

The following code displays the length of the array in the code as 10.

<?php

    $arr = array("HBWE", "FGTR", "HTNK", 4587, 4526, 4053, "AB12", "GB58", "TG45", "RE69");

    $arrLength = count($arr);

    echo $arrLength;

?>

The first statement creates an array with its elements at the same time.

The next statement (last-but-one) counts the number of elements and assigns the number to a new variable. The last statement prints (sends to browser) the value of the $arrLength variable, which is the length of the array.

Slicing an Array
Slicing an array means obtaining the values of a range of elements in the array. To do this, you use the following function (call).

    array array_slice ($array, $offset [, $length ] )

The portion of the array copied out is still an array, that is, the return value of the function is an array; that is why the syntax begins with the word, array.

The first argument, $array is the large array from where a range is to be copied out. The second argument, $offset is where to start the copy. The third argument is optional; it is the number of elements to be copied. Whenever you see an argument within square brackets in a syntax, it means that argument is optional.

Remember that index counting begins from zero, not 1. The following code slices a range from index 2 to index 6:

<?php

    $arr = array("HBWE", "FGTR", "HTNK", 4587, 4526, 4053, "AB12", "GB58", "TG45", "RE69");

    for ($i=0; $i<count($arr); ++$i)
        {
            echo $arr[$i], ' ';
        }

    echo "<br>";

    $slice_ar = array_slice($arr, 2, 3);

    for ($j=0; $j<count($slice_ar); ++$j)
        {
            echo $slice_ar[$j], ' ';
        }

?>

There are two for-loops: one to display the large array and the other to display the sliced array.

Note, if the argument for length is not given, then the slice will go from $offset to the end of the string.

In the for-loops the length of the large array is gotten from count($arr); and the length of the sliced array is gotten from count($slice_ar).

The output is:

HBWE FGTR HTNK 4587 4526 4053 AB12 GB58 TG45 RE69
HTNK 4587 4526

Array Functions
A function is a piece of code that accomplishes a task for you. You can write your own functions. The PHP  interpreter comes with some functions already written for you. Some of these functions are used with arrays. count() is an array function. array_slice() is also an array function. Explanation of other array functions are given below:

The array_push Function
Consider the array:

    $hisArr = ("HBWE", "FGTR", "HTNK", 4587, 4526, 4053, "AB12", "GB58", "TG45", "RE69");

The name of the array here is $hisArr. Also consider the array list content:

    "xxx", "yyy", "zzz"

You can append (add to the end) these three elements (values) to the large array. The simplified syntax to do this is:

    int array_push ($array, list)

In our example, you would have,

    array_push ($hisArr, "xxx", "yyy", "zzz");

Read and try the following code:

<?php

    $hisArr = array("HBWE", "FGTR", "HTNK", 4587, 4526, 4053, "AB12", "GB58", "TG45", "RE69");

    array_push($hisArr, "xxx", "yyy", "zzz");

    for ($i=0; $i<count($hisArr); ++$i)
        {
            echo $hisArr[$i], ' ';
        }

?>

The resulting array is:

    HBWE FGTR HTNK 4587 4526 4053 AB12 GB58 TG45 RE69 xxx yyy zzz

The output of the above code shows the appended list. The items of the output are separated by one space character, ' ' . The array_push function returns the new number of elements in the resulting array.

The array_unshift Function
The unshift function does the opposite of the push function. It prepends a list in front of the array, returning the new number of elements in the resulting array. The simplified syntax is:

    int array_unshift ($array, list)

In our case, you would have,

    array_unshift($hisArr, "xxx", "yyy", "zzz");

Try the following code,

<?php

    $hisArr = array("HBWE", "FGTR", "HTNK", 4587, 4526, 4053, "AB12", "GB58", "TG45", "RE69");

    echo count($hisArr), "<br>";

    $ret = array_unshift($hisArr, "xxx", "yyy", "zzz");

    echo $ret;

?>

The output is:

10
13

indicating that a list has been added. If you want to be sure if the list was prepended or appended, you have to add a for-loop to the code.

The array_pop Function
The pop function removes the last element from the array and returns it, shortening the original array by one element. The syntax is,

    value array_pop($array)

In our case, you would have,

    array_pop($hisArr);

Try the following code:

<?php

    $hisArr = array("HBWE", "FGTR", "HTNK", 4587, 4526, 4053, "AB12", "GB58", "TG45", "RE69");

    $returnValue = array_pop ($hisArr);

    echo $returnValue; echo "<br>";

    for ($i=0; $i<count($hisArr); ++$i)
        {
            echo $hisArr[$i], ' ';
        }

?>

The output is:

RE69
HBWE FGTR HTNK 4587 4526 4053 AB12 GB58 TG45

If array is empty (or if the argument is not an array), NULL will be returned.

The second statement above, pops of the last element from the array assigning the value removed to the new variable, $returnValue. The last-but-one line displays the returned (removed) value. The last line displays the original array, which is now missing its last element.

The array_shift Function
The shift function does the opposite of the pop function. It removes the first element from the array and returns it, shortening the original array by one element. The syntax is

    value array_shift($array);

In our case, you would have,

    array_shift($hisArr);

Try the following code:

<?php

    $hisArr = array("HBWE", "FGTR", "HTNK", 4587, 4526, 4053, "AB12", "GB58", "TG45", "RE69");

    $returnValue = array_shift($hisArr);

    echo $returnValue; echo "<br>";

    for ($i=0; $i<count($hisArr); ++$i)
        {
            echo $hisArr[$i], ' ';
        }

?>

The output is:

HBWE
FGTR HTNK 4587 4526 4053 AB12 GB58 TG45 RE69

The space between any function name and its opening bracket is optional. In the previous code, there is a one space character between pop and ( . In the above case, there is no space character between shift and ( ; it is optional.

The array_splice Function
The splice function removes a portion (range) of elements from the array and replaces the elements with that of some list, if that list is present. The resulting array may be larger or smaller than the original array depending on how many elements are in the replacement list. If there is no replacement list, then the resulting array is shorter. The splice function returns the removed list. The syntax is,

    removed_array array_splice($array, $offset, $length, list)

$array is the name of the original array. $offset is the index at which the removal starts. Remember, index counting begins from zero. $length is the number of consecutive elements to be removed. list, if present has the elements to replace the ones removed.

For our example, imagine that you want to remove 3 elements beginning from index 5 (which is position 6) and replace them with the list, ("xxx", "yyy", "zzz"). The splice function would be,

    array_splice($hisArr, 5, 3, array("xxx", "yyy", "zzz"));

The replacement list is actually an array, not just the values separated by commas.

Try the following code:

<?php

    $hisArr = array("HBWE", "FGTR", "HTNK", 4587, 4526, 4053, "AB12", "GB58", "TG45", "RE69");

    $ret_array = array_splice($hisArr, 5, 3, array("xxx", "yyy", "zzz"));

    for ($i=0; $i<count($ret_array); ++$i)
        {
            echo $ret_array[$i], ' ';
        }
    echo "<br>";
    for ($i=0; $i<count($hisArr); ++$i)
        {
            echo $hisArr[$i], ' ';
        }

?>

The output is:

4053 AB12 GB58
HBWE FGTR HTNK 4587 4526 xxx yyy zzz TG45 RE69

The second line has the splice function. The splice function returns the removed list (array). This is printed. The resulting array is also printed. Remember, if the list is not present in the splice function, the resulting original array would not have a replacement.

The use of the splice function can be more complicated than what I have explained. For this basic tutorial, let us allow things like this.

Indexed and Associative Array
The type of array described above, is an index array, in the sense that you use an index to access a value. The same PHP array can be coded so that you use a word or a phrase to access a value. In that case it would be called an Associative Array.

Associative Array

An Associative Example
The following list shows some fruits and their colors:

Apple => purple
Banana => yellow
Pear => green
Lemon => green

In the list you see that apple is purple, banana is yellow, etc. The => sign just shows that the item on the left corresponds to the item on the right. This is an associative list. Let us look at a typical indexed array list; a list of first names of some employees in a firm:

0 John
1 Mary
2 Peter
3 Augustine
4 Angela
5 Susan
6 Martin

In the indexed array list, the first column must always be indices; while the second column can have numbers or strings. In an associative list the first column is not necessarily indices; it can be made up of numbers and/or strings; the second column can also be made up of numbers and/or strings. The difference between an associative list and an indexed array list is that for an indexed array list, the first column always consists of indices (counting numbers from zero), but for an associative list the first column can be numbers and/or strings. The second column for an indexed array or associative list can be anything (numbers and/or strings). For the above two examples, the associative list has strings for the first column and the indexed array list has its unconditional indices.

Creating an Associative Array
The syntax to create an Associative Array is:

$arrayName = array(key1 => value1, key2 => value2, key3 => value3, …);

This is similar to the indexed array, except that here, each value has been replaced by the key/value pair. A key is a number or a string. A key is separated from its value by => (assignment operator followed by greater than operator).

You can give the name, fruitColor to the fruit example above. The following statement creates the associative array in PHP:

$fruitColor = array('Apple' => "purple", 'Banana' => "yellow", 'Pear' => "green", 'Lemon' => "green");

If a key is a phrase then it definitely has to be in quotes. The above statement can be typed in your code neatly as follows:

$fruitColor = array(
                                 'Apple' => "purple",
                                 'Banana' => "yellow",
                                 'Pear' => "green",
                                 'Lemon' => "green"
                              );

You are advised to place the keys in quotes; I will explain why, in a different series.

Accessing an Associative Array Value
The syntax to access an associative array value is:

    $arrayName['key']

You begin with a $ symbol, followed by the array name, and then a pair of square brackets. Inside the square brackets, you have the key of the corresponding value. The key may not be in quotes if it is one word (but this is not recommended). So to access the purple string above, you would type:

    $fruitColor['Apple']

This expression returns the corresponding value for the key.

Changing an Associative Array Value
You use the above expression to change an associative array value as follows:

    $arrayName[key] = newValue;

So to change the color of the apple in the array from purple to red, you would type:

    $fruitColor['Apple']= "red";

Try the following code, where the initial color for apple is displayed and then changed and re-displayed.

<?php

    $fruitColor = array(
                     'Apple' => "purple",
                     'Banana' => "yellow",
                     'Pear' => "green",
                     'Lemon' => "green"
                  );

    echo $fruitColor['Apple']; echo "<br>";

    $fruitColor[Apple]= "red";

    echo $fruitColor['Apple'];

?>

Creating Empty Associative Array before Assigning Values
You can create an empty associative array using either of the following statements:

    $arrayName = array();

    $arrayName;

The second one has a disadvantage, in the sense that you can later on assign an int or a float or any other data type to the variable.

After declaring the variable, you can then add elements one-by-one as follows:

$fruitColor['Apple']= "purple";
$fruitColor['Banana']= "yellow";

Accessing with a variable in place of a Key
You can access a value with a variable in place of a key. The following code segment illustrates this:

$herKey = 'Apple';
echo $fruitColor{$herKey};

Associative Array Functions
In PHP an associative array and an indexed array are actually the same array. The difference is how to code the PHP array. Array functions that are commonly used in associative mode are as follows:

The each Function
The syntax to use the each function is:

    array each($array)

This expression returns the next key/value pair and advances the array cursor to the next element. The scanning begins from the first element. Read and try the following code first before I continue to explain:

<?php

    $fruitColor = array(
                      'Apple' => "purple",
                      'Banana' => "yellow",
                      'Pear' => "green",
                      'Lemon' => "green"
                  );

     #first element
     $first_ret_arr = each($fruitColor);
     echo $first_ret_arr[0], "<br>";
     echo $first_ret_arr[1], "<br>";
     echo $first_ret_arr[key], "<br>";
     echo $first_ret_arr[value], "<br>";

     echo "<br>";

     #second element
     $second_ret_arr = each($fruitColor);
     echo $second_ret_arr[0], "<br>";
     echo $second_ret_arr[1], "<br>";
     echo $second_ret_arr[key], "<br>";
     echo $second_ret_arr[value], "<br>";

?>

The output is:

Apple
purple
Apple
purple

Banana
yellow
Banana
yellow

Now, for each key/value pair, the each() function returns an array of 4 elements. The return array is both an indexed array and an associative array. The first element has index of 0, and the value is the key of the key/value pair of the main array. The second element has index of 1, and the value is the value of the key/value pair of the main array. The third element has key with the text, 'key', and the value is again, the key of the key/value pair of the main array. And the fourth element has key with the text, 'value', where the value is again, the value of the key/value pair of the main array.

The output of the above code is for the first 2 iterations.

The array_keys Function
The syntax of the keys function is:

   array array_keys($array)

It returns an indexed array of all the keys in the associative array. Try the following code:

<?php

    $fruitColor = array(
                      'Apple' => "purple",
                      'Banana' => "yellow",
                      'Pear' => "green",
                      'Lemon' => "green"
                  );

    $arr = array_keys($fruitColor);

    for ($i=0; $i<count($arr); ++$i)
        {
            echo $arr[$i], ' ';
        }

?>

The output is:

    Apple Banana Pear Lemon

The order of the return keys again is not predetermined (not the way they were typed).

The array_values Function
It returns an indexed array of all the values in the associative array:

    array array_values($array)

Try the following code:

<?php

    $fruitColor = array(
                      'Apple' => "purple",
                      'Banana' => "yellow",
                      'Pear' => "green",
                      'Lemon' => "green"
                  );

    $arr = array_values($fruitColor);

    for ($i=0; $i<count($arr); ++$i)
        {
            echo $arr[$i], ' ';
        }

?>

The output is:

purple yellow green green

Security Concerns

Ambiguity with Boolean Type
The value, null is the only value of the type, null. The Boolean type has two values which are true and false. However, null is equal to false but not identical to false. The value of an index or key may be, null, which is a valid value. You may want to test if null has been returned; but if you instead compare (by equality) it to false, you will have the wrong answer. To have the correct answer, you have to use the identical operator and compare null to null.

The test ambiguity between true and 1 or -1 or  '1' or '-1' or 'text' still exist for the array value. The test ambiguity between false and 0, or '0' or null or '' or "" also exist for the array value.

Combined Indexed Array and Associative Array
PHP allows you to combine indexed and associative arrays as the following example shows:

<?php

    $fruitColor = array(
                      0 => 'John',
                      'Apple' => "purple",
                      1 => 'Mary',
                      'Banana' => "yellow",
                      2 => 'Peter',
                      'Pear' => "green",
                      3 => 'Augustine',
                      'Lemon' => "green",
                      4 => 'Angela'
          fnbRp;  &jbcsâîrRp;&nbqp3nâsx{*æsQ3© 8`z>\bò.nBwp; &~b³x;tn"{p+f/z ($i=0:  i<:Aëý}t %frdi°Kolor); :+àa©&ncqô3'n`sz*./jsP;¦vrS47&~`rp¿&fbt;njrð;&,âspy{
&lb{q;&nb3p»n¤óp+dkóô;ff`s8:&Obsp9&fcsp;&Nbû`"nBsà+ffbsp+&.jrr¿&oB7T+Ü1@{ dnruitAofnzX$a],¤' ';>bj?v&b{Q&nb{xjbsp"nbq2; ¦nb1p;  +}üjr|
?>:<ær:Thg gttpu4`iR,b26=bö~JoIn erH"PetmrUtùódine Angela tCAR"ygt caj c'o,)qhå0i`lE~`~ariáb,',$i$hqu`zME¢tdtáctÅL€Æôu!oeys. o @ögi$such a probleí. /n¤nwt@_o¯zaOe dHe ynDeøud arvai"a~``lje ass/ci@tive`arSc]¦­r06=br><3trNng>Repeatdd¤Index os ÖepEaôud Key
P@P`gew¤~mt#gã|rla)n Vhel io a2raX index or ëexbís!paè¤c?à. It simpny(hgnorus`|he rmpApyvyk.k"eycápt tè5 lH{u ïnel Try!tìe follow)ncc='-—?B~><ær.&,|;?php
4bR: &nbsð;&,Bsð+.lBq;$frtiðGo|mr ="ezccy(
&ncsô9&f#s06O"{P;¦>bsQ; .nBwp;6n"[x»jfs`9&nbó`;$fbsp;&nbsr;.ïbó2;dnbsp86â#{p;fjbBr;   {&nCwp+dn`RX:¦þ"s2&nbs`p¨­&g6;$'Zmhn',
&nbsð:&¨bsp;¢nr3q;"nbsp;                  0 => 'Mary',
                      1 => 'Peter',
                      1 => 'Augustine',
                      2 => 'Angela',
                      'dd' => 'Martin',
                      2 => 'Susan',
                      'dd' => 'Grace'
                  );

    echo count($fruitColor), "<br>";

    for ($i=0; $i<count($fruitColor); ++$i)
        {
            echo $fruitColor[$i], ' ';
        }

    echo "<br>";

    echo $fruitColor['dd'], "<br>";

?>

The output is:

4
Mary Augustine Susan
Grace

To avoid such a problem, just be carefull how you code the array. Normally, values can repeat, but index or key should not repeat.

That is it for this part of the series. We stop here and continue in the next part.

Chrys

Related Links

Basics of PHP with Security Considerations
More Related Links
Pure PHP Mailsend - sendmail
PurePHP MySQL API
Using the PurePHP MySQL API
Cousins
JavaScript/ECMAScript Course
Perl Course

BACK NEXT

Comments

Become the Writer's Follower
Send the Writer a Message