Broad Network


PHP Indexed Array Basics with Security Considerations

PHP Arrays with Security Considerations

Foreword: In this part of the series, I talk about indexed array in PHP.

By: Chrysanthus Date Published: 7 Nov 2018

Introduction

This is part 2 of my series, PHP Arrays with Security Considerations. In this part of the series, I talk about indexed array in PHP. You should have read the previous part of the series before coming 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 the 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 Boolean or a NULL or even an array.

You can create an array and at the same time, give it the first value as follows:

$arr[] = value;

This creating method with square brackets, has some weaknesses - see below.

The value to the element of an array can be a scalar (number, Boolean, string), a compound type (array, object, callable, iterable) or a special type (resource, null). In this tutorial I talk only about scalar values as array values.

Populating an Array
An empty array created is said to have no population because it has no items. You can populate (add items) to the 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 it with $.

You can add elements to the array that already has elements, in the same way.

When no index is specified, the maximum index plus 1 is used. Try the following code:

<?php

    $arr = array("HBWE", "FGTR", "HTNK");
    $arr[] = "some thing";
    echo $arr[3];

?>

The output is:

    some thing

The new index was, 2 + 1 = 3;

Accessing an Element in the 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 element's 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.

Possible Types for Index
An integer, float, string, Boolean and null, can be used as index.

Negative integers can also be used. Try the following code:

<?php

    $arr = array(0 => "aaa", 1 => "bbb", -6 => "ccc");

    echo $arr[1], '<br>';
    echo $arr[-6];

?>

The output is:

    bbb
    ccc

The integers do not have to be consecutive numbers. Try the following:

<?php

    $arr = array(-6 => "aaa", -3 => "bbb", 0 => "ccc", 2 => "ddd", 5=> "eee");

    echo $arr[-6], '<br>';
    echo $arr[-3], '<br>';
    echo $arr[0], '<br>';
    echo $arr[2], '<br>';
    echo $arr[5], '<br>';

?>

The output is:

    aaa
    bbb
    ccc
    ddd
    eee

Allowing negative integers and non-consecutive sequence of integers can be problematic - see below. Indexing does not also have to start from zero. It can sart from any number.

A float as index is made the integer by truncating the decimal part. Try the following:

<?php

    $arr = array(2.5 => "aaa", 2 => "bbb", 4.6 => "ccc", 4 => "ddd");

    echo $arr[2.5], '<br>';
    echo $arr[2], '<br>';
    echo $arr[4.6], '<br>';
    echo $arr[4], '<br>';

?>

The output is:

    bbb
    bbb
    ddd
    ddd

When more than one index are the same, the last one and its value are considered, and the previous elements are ignored. That explains why this output is what it is. Using float as index is problematic - see below.

The integer can be typed as a string for an index. Try the following code:

<?php

    $arr = array(8 => "aaa", '8' => "bbb", '08' => "ccc");

    echo $arr[8], '<br>';
    echo $arr['8'], '<br>';
    echo $arr['08'], '<br>';

?>

The output is:

    bbb
    bbb
    ccc

Note that an integer in quotes, is converted to an integer. That is why the the first and second line for the output are the same (the second element is considered because of the ultimate repetition of keys).

If the integer in the string is preceded by +, it will not be converted (or stored) as an integer.

An integer with preceding zero as a string, for the index, remains as a string and is not converted to the integer. This means you cannot add 1 to '08' to have the index 9. Using a string as index is problematic - see below.

A key of Boolean true is converted to 1 for an index. A key of Boolean false is converted to 0 for an index. Try the following:

<?php

    $arr = array(false => "aaa", true => "bbb");

    echo $arr[0], '<br>';
    echo $arr[1], '<br>';

?>

The output is:

    aaa
    bbb

Using Boolean values (true or false) as keys is also problematic - see below.

A null value is converted to the empty string, "" for an index. Try the following code:

<?php

    $arr = array(0 => "aaa", null => "bbb");

    echo $arr[0], '<br>';
    echo $arr[""], '<br>';

?>

The output is:

    aaa
    bbb

Using NULL as keys is problematic - see below.

Note: The interpolation can take place in both the key of the array definition, or in the square brackets when accessing the array value.

Arrays cannot be used as keys. Doing so will result in a warning: Illegal offset type. This is not a fatal error which stops the program. The array element is ignored and the program continues to run. Ignoring an element leads to NULL for the value. Try the following code:

<?php

    $arra = array("aaa", "bbb");

    $arr = array(0 => 'boy', $arra => 'girl');

    echo $arr[0], '<br>';
    echo $arr[$arra], '<br>';
    echo 'seen';

?>

I tried the code and I had:

    Warning: Illegal offset type in C:Apache24htdocstemp.php on line 5
    boy

    Warning: Illegal offset type in C:Apache24htdocstemp.php on line 8

    seen

No value was printed for the array ($arra) as key.

Objects cannot be used as keys. Doing so will result in a warning: Illegal offset type. This is not a fatal error which stops the program. The array element is ignored and the program continues to run. Ignoring an element leads to NULL for the value. Try the following code:

<?php

    class Calculator
        {
            public $num = 9;

        }

    $myObject = new Calculator();

    $arr = array(0 => 'boy', $myObject => 'girl');

    echo $arr[0], '<br>';
    echo $arr[$myObject], '<br>';

    echo 'seen';

?>

I tried the code and I had:

    Warning: Illegal offset type in C:Apache24htdocstemp.php on line 11
    boy

    Warning: Illegal offset type in C:Apache24htdocstemp.php on line 14

    seen

No value was printed for the object ($myObject) as key.

Security Considerations

Creation of an Array
You can create an array by declaring without assignment, as follows

    $arr;

It is not crear if this variable holds an array or a scalar or some other variable. So, you the programmer can easily assign some other value to it down in the program. Then when you need the array, you get maybe a string, which in one circumstance, would behave like an array.

Prevention: Develop the habit of initializing your PHP variables during declaration. To know if a variable is in use up in the program, use the PHP predefined isset() function. Or, do not use this method of creating array, at all.

Another way to create an array, is as follows:

    $arr[] = value;

A problem here, is that, if $arr already had some elements, value will be added with the index that is 1 higher the highest index that was in the array. If no index was there, then the index given would be 0.

Prevention: How can you create an array that already has elements? Use the isset() function to know if the array is already in use, up in the program. If it is already in use, choose another name for the array. Or, do not use this method of creating array, at all.

The [] does not have to be empty when creating an array. You can create an array this way with some other index, other than 0. You may end up over-writing the value of some other element, which was already there. Or, you may actually add a new element (which is not bad). If $arr were a string, you would end up modifying the string. Try the following code:

<?php

    $str = 'word';

    $str[1] = 'avatar';

    echo $str, '<br>';

?>

The output is:

    ward

Imagine the damage this would cause if $str were a password, because you tried to create an array, this way.   

Prevent this by first checking if the variable is already in use, with the isset() function. Or, do not use this method of creating array, at all.

New Index
When you delete elements from an array, there is no re-indexing. When you add a new index to the array, just by adding a value (no key specified), the new index is the largest index before, plus 1. Assume that you had an array with the largest index, 12 and you delete the element, implying that there is no more index of 12. If you now add a value (without index) to the array, the new index would be 13. This is not usually a problem.

Occasionally you will need re-indexing after deleting elements. Use the array_values() function as in the following code:

<?php

    $arr = array(0=>'aa', 1=>'bb', 2=>'cc', 3=>'dd', 4=>'ee');

    unset($arr[2]);
    unset($arr[4]);

    foreach ($arr as $key => $value)
        echo $key, ' => ', $value, '<br>';

    array_push($arr, 'ff');

    echo '<br>';

    foreach ($arr as $key => $value)
        echo $key, ' => ', $value, '<br>';

    $arr = array_values($arr);

    echo '<br>';

    foreach ($arr as $key => $value)
        echo $key, ' => ', $value, '<br>';

    array_push($arr, 'gg');

    echo '<br>';

    foreach ($arr as $key => $value)
        echo $key, ' => ', $value, '<br>';

?>

The unset() function deletes an element. Reading the value of the deleted element, using the key, returns NULL.

The output is:

    0 => aa
    1 => bb
    3 => dd

    0 => aa
    1 => bb
    3 => dd
    5 => ff

    0 => aa
    1 => bb
    2 => dd
    3 => ff

    0 => aa
    1 => bb
    2 => dd
    3 => ff
    4 => gg

Read the code (program) to appreciate the output.

Reading the Value of an Array Element
You use a key (index) to read the value of an element; if the element exists, the reading returns the value. If the element has been deleted, the reading returns null. However, null is a valid value in PHP. The value of an element can actually be null. 0, "" and false can be evaluated as null later in the program

Solution: You should know in advance, the different possible values that an element can have. When you read the value, test for null with the === (or !==) operator.

Non-Consecutive Indices
Non-consecutive indices is usually not a problem. However, when it is necessary, do re-indexing.

Negative Indices
Nobody can work with negative indices as well as he/she can work with positive indices. Use negative indices only when you have to, such as in scientific work.

Types and Index
A float as index is made the integer by truncating the decimal part. You should convert the float to integer first, before you use it as array key index; otherwise you may have an algorithm related to the array, later in the program, that you will not be able to explain.

A string such as '+8' or '08', which would normally be casted to an integer, is not converted to the integer. You should convert any string you want as integer, to integer first, before you use it as array key index; otherwise you may have an algorithm related to the array, later in the program, that you will not be able to explain.

A key of Boolean true is converted to 1 for an index. A key of Boolean false is converted to 0 for an index. You should convert any Boolean value you want as integer, to integer first, before you use it as array key index; otherwise you may have an algorithm related to the array, later in the program, that you will not be able to explain.

A null value is converted to the empty string, "" for an index. Do you really want to use an empty string as key? Solution: If you really must use an empty string as key, then give the key a string value, such as "nn" or "nullKey".

An array or object cannot be used as a key. Doing so will result in a warning: Illegal offset type. This is not a fatal error which stops the program. The array element is ignored and the program continues to run. Ignoring an element leads to NULL for the value. Solution: Do not use an array or object as key.

In PHP, the same array can be used as indexed array or an associative array, or an array with both types of keys. I have separated it into three types of arrays, to better explain it.

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
White Space in PHP
PHP Data Types with Security Considerations
PHP Variables with Security Considerations
PHP Operators with Security Considerations
PHP Control Structures with Security Considerations
PHP String with Security Considerations
PHP Arrays with Security Considerations
PHP Functions with Security Considerations
PHP Return Statement
Exception Handling in PHP
Variable Scope in PHP
Constant in PHP
PHP Classes and Objects
Reference in PHP
PHP Regular Expressions with Security Considerations
Date and Time in PHP with Security Considerations
Files and Directories with Security Considerations in PHP
Writing a PHP Command Line Tool
PHP Core Number Basics and Testing
Validating Input in PHP
PHP Eval Function and Security Risks
PHP Multi-Dimensional Array with Security Consideration
Mathematics Functions for Everybody in PHP
PHP Cheat Sheet and Prevention Explained
More Related Links

Cousins

BACK NEXT

Comments