Broad Network


PHP Array Functions with Security Considerations

PHP Arrays with Security Considerations

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

By: Chrysanthus Date Published: 7 Nov 2018

Introduction

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

The Length of an Array
The length of an array is the number of elements in the array. 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 (or the object).

The following code displays the length of the array 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.

The function returns the number of elements counted. If the number of elements is zero, it will return zero. If $var is NULL, it still returns zero. If $var is not an object or not an array or not null, it returns 1.

As you can see, the count() function has some issues, which I address later in this series.

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 from. 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 4 (inclusive):

<?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

The function returns the slice. If the offset is larger than the size of the array then it returns an empty array.

If you want to preserve keys and do re-indexing, use the array_slice() function as follows, where $offset = 0:

<?php

    $arr = array(0=>'A', 'aa' => 'woman', 1=>'B', 2=>'C', 'bb' => 'man', 3=>'D', 4=>'E');

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

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

    array_push($arr, 'F');

    echo '<br>';

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

    $arr = array_slice($arr, 0);

    echo '<br>';

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

    array_push($arr, 'G');

    echo '<br>';

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

?>

The output is:

0 => A
aa => woman
1 => B
bb => man
3 => D

0 => A
aa => woman
1 => B
bb => man
3 => D
5 => F

0 => A
aa => woman
1 => B
bb => man
2 => D
3 => F

0 => A
aa => woman
1 => B
bb => man
2 => D
3 => F
4 => G

You slice from the beginning to the end of the array.

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");

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_push() function has some issues, which I will explain later in this series.

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_pop() function has some issues, which I will address later in this series.

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 those 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.

The array_keys() Function
The syntax for 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 array_values() Function
It returns an indexed array of all the values in the associative array. Syntax is:

    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

The current() Function
The syntax for the current() function is:

    array current($array)

Every array has an internal pointer to its "current" element, which is initialized to the first element inserted into the array.

The current() function simply returns the value of the array element that's currently being pointed to by the internal pointer. It does not move the pointer in any way. If the internal pointer points beyond the end of the elements list or the array is empty, current() returns FALSE.  

The current() function has some issues, which I will address later in this series.

The key() Function
The syntax for the key() function is:

    array key($array)

The key() function simply returns the key of the array element that's currently being pointed to by the internal pointer. It does not move the pointer in any way. If the internal pointer points beyond the end of the elements list or the array is empty, key() returns NULL.

The next() Function
The syntax for the next() function is:

    array next($array)

next() behaves like current(), with one difference. It advances the internal array pointer one place forward before returning the element value. That means it returns the next array value and advances the internal array pointer by one.

The next() function returns the array value in the next place that's pointed to by the internal array pointer, or FALSE if there are no more elements.

The next() function has some issues, which I will address later in this series.

The prev() Function
The syntax to use the prev() function is:

    array prev($array)

prev() behaves just like next(), except it rewinds the internal array pointer one place instead of advancing it.

This function returns the array value in the next place that's pointed to by the internal array pointer, or FALSE if there are no more elements.

The prev() function has some issues, which I will address later in this series.

The end() Function
The syntax for the end() function is:

    mixed end($array)

end() advances array's internal pointer to the last element, and returns its value.

The function returns the value of the last element or FALSE for empty array.

This function has some issues, which I address later in this series.

The reset() Function
The syntax for the reset() function is:

    mixed reset($array)

reset() rewinds array's internal pointer to the first element and returns the value of the first array element.

The function returns the value of the first array element, or FALSE if the array is empty.

The reset() function has some issues, which I address later in this series.


The above six functions are put into action in the following code. Read through the code. Try it. Read through the output to appreciate the use of the functions.

<?php

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


    while (key($fruitColor))
        {
            echo key($fruitColor), ' => ', current($fruitColor), '<br>';
            next($fruitColor);
        }

    echo '<br>';

    end($fruitColor); //point to last element of array
    while (key($fruitColor))
        {
            echo key($fruitColor), ' => ', current($fruitColor), '<br>';
            prev($fruitColor);
        }

    echo '<br>';

    reset($fruitColor); //point to first element of array
    while (key($fruitColor))
        {
            echo key($fruitColor), ' => ', current($fruitColor), '<br>';
            next($fruitColor);
        }

?>

The output is:

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

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

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

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