Pchp.Library.Arrays.array_pad C# (CSharp) Method

array_pad() public static method

Pads array to the specified length with a value. If the length is negative adds |length| elements at beginning otherwise adds elements at the end. Values with integer keys that are contained in the source array are inserted to the resulting one with new integer keys counted from zero (or from |length| if length negative).
The argument is a null reference.
public static array_pad ( PhpArray array, int length, PhpValue value ) : PhpArray
array Pchp.Core.PhpArray The source array.
length int The length of the resulting array.
value Pchp.Core.PhpValue The value to add in array.
return Pchp.Core.PhpArray
        public static PhpArray array_pad(PhpArray array, int length, PhpValue value)
        {
            if (array == null)
            {
                // PhpException.ArgumentNull("array");
                // return null;
                throw new ArgumentNullException();
            }

            // number of items to add:
            int remains = Math.Abs(length) - array.Count;

            // returns unchanged array (or its deep copy if called from PHP):
            if (remains <= 0) return array;

            PhpArray result = new PhpArray(array.Count + remains);

            // prepends items:
            if (length < 0)
            {
                while (remains-- > 0) result.Add(value);
            }

            // inserts items from source array
            // if a key is a string inserts it unchanged otherwise inserts value with max. integer key:  
            var iterator = array.GetFastEnumerator();
            while (iterator.MoveNext())
            {
                var key = iterator.CurrentKey;
                if (key.IsString)
                    result.Add(key, iterator.CurrentValue);
                else
                    result.Add(iterator.CurrentValue);
            }

            // appends items:
            if (length > 0)
            {
                while (remains-- > 0) result.Add(value);
            }

            // the result is inplace deeply copied on return to PHP code:
            //result.InplaceCopyOnReturn = true;
            return result;
        }