Non-destructive array extending in PHP

Non-destructive array extending in PHP

Created:25 May 2017 13:30:48 , in  Web development

Non-destructive extending of array in PHP

Suppose you have to extend a PHP array by inserting some value at a particular index of it without destroying other pieces of data stored in the array. In PHP Extending array non-desctructively by prepending an item can be achieved with function array_unshift. Similarly, the language provides function array_push for appending items to an array. Nothing too difficult or new here so far.

The task becomes slightly more involved when a piece of data has to be inserted somewhere in-between the first and the last item of an array. Extra difficulty of this case arises from the need of shifting items currently in the array that are stored at indices greater or equal to the chosen to insert new piece of data at.

ItemAt class method

To deal with problems like this, I wrote a class method "itemAt". It provides functionality similarly to array_unshift and array_push do and also deals with the more complex case seamlessly:

Here is listing of the method:


/*
  ArrayInsert::itemAt 
  Description: non-destructive extending of PHP number-indexed array
  Author: Sylwester Wojnowski
  WWW: wojnowski.net.pl

  paremeters:
    $arr - number-indexed Array
    $k - index to insert $item in $arr 
    $item - piece of data to be inserted in $arr 

  return value
    Extended array
*/
class ArrayInsert{
  public static function itemAt($arr,$k,$item){
    $j = 0;
    $n = count($arr);
    if($k >= $n){ 
      $arr[] = $item;
      return $arr;    
    }
    while( $j < $n ){
      if($j === $k){
        $i = -1;
        # items at the indices >= to $k have to be moved to the right 
        while($i + $n >= $j ){
         $arr[ $i + $n + 1 ] = $arr[$i + $n];
         if($i + $n === $j){
           $arr[$j] = $item;
           break;
         }
         $i--;
        }
      }
      $j++;
    }
    return $arr;
  }
}

Usage examples

Here are some use examples involving NULLs, strings, arrays and objects:

Inserting a string in the middle of array:


ArrayInsert::itemAt(array('a','c'),1,'b')
=> array('a','b','c')

Inserting an array in the middle of another array


ArrayInsert::itemAt(array('absinth','sake'),1,array('bitter ale','cask ale','mead'))
=> array('absinth',array('bitter ale','cask ale','mead'),'sake')

Inserting an object at the beginning of array:


$guitars = array(
  (object)array(
    'brand' => 'Jackson',
    'model' => 'King V' 
  ),
  (object)array(
    'brand' => 'Gibson',
    'model' => 'Les Paul Studio' 
  ),
  (object)array(
    'brand' => 'Schecter',
    'model' => 'Hellriser C1' 
  )
);
$bc_rich = (object)array('brand' => 'BC Rich', 'model' => 'Warlock');
$guitars = ArrayInsert::itemAt($guitars,0,$bc_rich); 

Guitars array has 4 items now, with the first items brand property value being "BC Rich".

Inserting NULL at a particular index.


ArrayInsert::itemAt(array('a',null),0,null)
=> array(null,'a',null)

Inserting multiple items in an array non-destructively

Now suppose you need to insert an array of items into your current array with first of the items to be put in at some particular index and the rest behind it.

One way to do that is by adding method "flatten" to ArrayInsert class. Here is a listing of this method:


public static function flatten($arr){
  return iterator_to_array(
    new RecursiveIteratorIterator(new RecursiveArrayIterator($arr))
  ,false);
}

And here is an example of use of "flatten" and "arrayAt" together:


# inserting an array of strings with the first of them being added at index 1
ArrayInsert::flatten(
  ArrayInsert::itemAt(array(),1,array('red','blue',array('orange','pink'),'green')))
);
=> array('red','blue','orange','pink','green')

Final thoughts

Regardless of programming language, number-indexed arrays are commonplace in computer programming. It is vital to have some reliable tools to deal with them effectively. Presented pieces of code are such invaluable little tools.I hope they will prove a useful addition to your toolkit.

Feedback and shares are welcome.

This post was updated on 25 May 2017 16:22:10

Tags:  php 


Author, Copyright and citation

Author

Sylwester Wojnowski

Author of the above article, Sylwester Wojnowski, is sWWW admin and owner.He enjoys doing Maths and studying algorithms, writing code in scripting and command languages, Thrash Metal music and playing electric guitar.

Copyrights

©Copyright, 2017 Sylwester Wojnowski. This article may not be reproduced or published as a whole or in parts without permission from the author. If you share it, please give author credit and do not remove embedded links.

Computer code, if present in the article, is excluded from the above and licensed under GPLv3.

Citation

Cite this article as:

Wojnowski, Sylwester. "Non-destructive array extending in PHP." From sWWW - Code For The Web . https://wojnowski.net.pl//main/index/non-destructive-array-extending-in-php