Broad Network


PHP Associative Array with Security Considerations

PHP Arrays with Security Considerations

Foreword: In this part of the series, I talk about PHP Associative Array with Security Considerations.

By: Chrysanthus Date Published: 7 Nov 2018

Introduction

This is part 3 of my series, PHP Arrays with Security Considerations. In this part of the series, I talk about PHP Associative Array with Security Considerations. You should have read the previous parts of the series before coming here, as this is the continuation.

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.

In this tutorial I talk only about associative list or arrays, where the first column consists of only strings.

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 creation, 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, later in this series.

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 by giving it the first value as follows:

$arr['key'] = value;

This creating method with square brackets, has some weaknesses - I talked about the weakness with prevention, in one of the previous parts of the series.

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.

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 the key. The following code segment illustrates this:

$herKey = 'Apple';
echo $fruitColor[$herKey];

Possible Types for Key
An integer, float, string, Boolean or null, can be used as key.

A float in quotes can be used as key. The string is not converted to a number. Try the following:

<?php

    $arr = array('2.5' => "aaa", "4.6" => "bbb");

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

?>

The output is:





    aaa
    bbb

The output shows that the float in quotes (string) is neither converted to the integer nor converted to the float number.

When more than one string or index as key, is the same, the last one and its value are considered, and the previous elements are ignored. Try the following:

<?php

    $arr = array('xx' => "aaa", 'yy' => "bbb", 'xx' => "ccc", 'yy' => "ddd");

    echo $arr['xx'], '<br>';
    echo $arr['yy'], '<br>';
    echo $arr['xx'], '<br>';
    echo $arr['yy'], '<br>';

?>

The output is:

    ccc
    ddd
    ccc
    ddd

which shows that the last element is considered for repeated keys.

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 the 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 key, 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 null value is converted to the empty string, "" for a key. Try the following code:

<?php

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

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

?>

The output is:

    aaa
    bbb

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

<?php

    $arr = array('kk' => "aaa", "" => "bbb");

    echo $arr['kk'], '<br>';
    echo $arr[null], '<br>';

?>

The output is:

    aaa
    bbb

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.

Bare Word as Key
You can make a scalar value constant to a variable, and the value to the variable will never change in the script. Try the following code with the comment (two forward slashes) in place:

<?php

    const pii = 3.14;

    echo pii;

    //pii = 4.77;

?>

Note the use of the reserved word, const. Note that the variable, pii does not have $. The output is:

    3.14

A variable without $ is called a bare word. The value of 3.14 assigned to pii cannot be changed for pii.

Remove the comment (two forward slashes) and try the code again.

Note that the program (script) does not even run because of the fatal error.

Bare word as key: Try the following code where the key, fruits is in quotes, "

<?php

    $arr = array('one' => "aaa", 'fruits' => "oranges", 'three' => "ccc");

    echo "I need some " . $arr['fruits'] . " after meal.";

?>

The output is:

    I need some oranges after meal.

where the array variable has been replaced by its value, oranges.

Now, try the following code where the array variable is within double quotes, with fruits in single quotes.

<?php

    $arr = array('one' => "aaa", 'fruits' => "oranges", 'three' => "ccc");

    echo "I need some $arr['fruits'] after meal.";

?>

The array variable was supposed to have expanded to its value, but it did not. Instead, the script did not run because of a fatal error, due to the presence of the quotes around fruits.

Now, a key such as fruits should work in that position. Try the following code where the single quotes have been removed:

<?php

    $arr = array('one' => "aaa", 'fruits' => "oranges", 'three' => "ccc");

    echo "I need some $arr[fruits] after meal.";

?>

The script now works and the output is:

    I need some oranges after meal.

Use of bare word as key outside doubled quoted string also works; you may just have a warning message and not a fatal error. Try the following code:

<?php

    $arr = array('one' => "aaa", 'fruits' => "oranges", 'three' => "ccc");

    echo $arr[fruits];

?>

I tried it and I had:

    Warning: Use of undefined constant fruits - assumed 'fruits' (this will throw an Error in a future version of PHP) in C:Apache24htdocstemp.php on line 5
    oranges

It still worked, but with a warning. Warning means you may or may not have wrong results down in the code, related to the issue.

Using a non-constant (bare word) in the place of a constant as in the above code samples, is a weakness in PHP.

The real problem is that, if the bare word, e.g. fruits is a predefined constant in PHP or a constant you have defined or reserved word in PHP, you may not get the result you want. The number of constants and reserved words in PHP increases with the PHP versions. So, you may use a word like fruits today, which works; when the same script is used later with a newer version, you will have a different result. Already, you cannot use the bare words, empty or default as key without quotes, because they are reserved words.

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.

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.

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.

Bare Words as Keys
You should use word keys in quotes, but within double quotes, you should use them as bare words. Used of bare words, conflict with current constants and constants to come.

Solution: Always use word keys in quotes. If you are to use it in a double quoted string, separate the string, isolating the array key variable as in the following code:

<?php

    $arr = array('one' => "aaa", 'fruits' => "oranges", 'three' => "ccc");

    echo "I need some " . $arr['fruits'] . " after meal.";

?>

In this way, you always use word keys in quotes.

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