JsArray - ahamed/JsPhp GitHub Wiki

Array Methods

Here I cover most of the useful array methods. We now learn them one by one. These methods are documented in alphabetical order.

You can declare a JsArray simply-

$array = new JsArray([
    'name' => 'John Doe',
    'email' => '[email protected]',
    'age' => 24,
    'gender' => 'male'
]);

Note that the $array here is not a native php array, rather it's an instance of JsArray. But don't worry, you can perform array operations like-

$name = $array['name'];
$email = $array['email'];

print_r($name); // "John Doe"
print_r($email); // "[email protected]"

You can change or set new value in the $array like native.

// Changing existing value
$array['name'] = 'Alice Bob';
print_r($array['name']); // "Alice Bob"

// Set a new value.
$array['phone'] = '12345678';
print_r($array['phone']); // "12345678" 

Even you can iterate through the $array like native array.

foreach ($array as $key => $value)
{
    echo $key . " => " . $value . "\n";
}

// Output:
// "name" => "Alice Bob"
// "email" => "[email protected]"
// "age" => 24
// "gender" => "male"
// "phone" => "12345678"

But note that, you cannot perform any native php array methods on the $array because it still an instance of JsArray. So, for getting the array elements simply call the get() method on the $array instance.

$elements = $array->get();
print_r($elements);
// Expected output: ['name' => 'Alice Bob', 'email' => '[email protected]', 'age' => 24, 'phone' => '12345678']

Now you can perform any native PHP array methods on $elements array.

# at

The at() method returns a specific index value of an array. This is similar to the array's square bracket index but the benefit over the square bracket is that it can brings negative index value. If you put -1 as index then it returns the last value of the array. If the index is not in the range then it throws OutOfRangeException.

Example

$array = new JsArray([1, 2, 4, 5, 6]);
print_r($array->at(0)); // Output: 1
print_r($array->at(3)); // Output: 5
print_r($array->at(-1)); // Output: 6
print_r($array->at(-4)); // Output: 2
print_r($array->at(6)); // Output: throws OutOfRangeException
print_r($array->at(-6)); // Output: throws OutOfRangeException

Syntax

$value = $array->at($index);

Parameters

  • $index The index array index value. This index will be an integer value ranged [0, length - 1].

Return Value

The value of the array at the corresponding index position. If index is not within the range [0, length - 1] then throws OutOfRangeException.

# concat

The concat() method is used to merge two or more arrays. This is not change the original array but returns a new array after merging.

Example

$array1 = new JsArray([1, 2, 3]);
$array2 = new JsArray([4, 5, 6]);
$newArray = $array1->concat($array2);

print_r($newArray);
// Expected output: JsArray [1, 2, 3, 4, 5, 6]

Syntax

$newArray = $array->concat([$value1 [, $value2 [, ...[, $valueN]]]]);

Parameters

  • $valueN (optional) Arrays and/or scalar values to concatenate into a new array. If all $valueN parameters are omitted then concat returns the copy of the original array.

Return Value

A new JsArray instance with concatenated elements.


# every

The every() method tests whether all items in the array pass the test implemented by the user callback function.

Example

$array = new JsArray([1, 3, 5, 7]);
$isAllItemsOdd = $array->every(
    function ($item) {
        return $item % 2 === 1;
    }
);

var_dump($isAllItemsOdd);
// Expected output: bool(true)

// Using php >= 7.4 Arrow Function
$isAllItemsEven = $array->every(fn($item) => $item % 2 === 0);

var_dump($isAllItemsEven);
// Expected output: bool(false)

Syntax

$isPassed  = $array->every($callback($item [, $index [, $key]]));

Parameters

  • $callback A function to test for each item. This function takes three arguments. One required and two optional.
    • $item The current item to test on.
    • $index (optional) A zero based index of the current item.
    • $key (optional) The key of the current item of the array being processed.

Return Value

Boolean. True if all the items pass the user defined test and False otherwise.


# fill

The fill() method changes all elements by a static value within a range [$start, $end). The $start is zero based index number and the end is also zero based index number but the $end index does not change. I.e. the $end is exclusive.

  • If the $start is negative then it's treated as $array->length + $start but the summation never be negative. If negative then it takes 0 as $start value.
  • If the $end is negative then it's treated as $array->length + $end but the summation never be negative. If negative then it takes 0 as $end value.

Example

$array = new JsArray([1, 2, 3, 4, 5]);

$array->fill(0);
print_r($array);
// Expected output: JsArray [0, 0, 0, 0, 0]

$array->fill(2, 2, 4);
print_r($array);
// Expected output: JsArray [0, 0, 2, 2, 0]

$array->fill(3, -2);
print_r($array);
// Expected output: JsArray [0, 0, 2, 3, 3];

Syntax

$array->fill($value [, $start [, $end]]);

Parameters

  • $value Value to fill the array with. (Note all elements in the array will be this exact value.)
  • $start (optional) Start index, default 0.
  • $end (optional) End index, default $array->length

Return Value

Modified JsArray instance filled with $value.


# filter

The filter() method creates a new array with all elements that pass the user provided function. If you apply the filter method to an associative array then it automatically preserves the keys of the array. If the array is a hybrid array i.e. it contains both numeric keys and string keys then it preserves the string keys but the numeric keys will be rebased from zero.

Example

$array = new JsArray([1, 2, 3, 4, 5, 6]);
$evenNumbers = $array->filter(
    function ($item) {
        return $item % 2 === 0;
    }
);
print_r($evenNumbers);
// Expected output: JsArray [2, 4, 6]

// Associative array example
$array = new JsArray(['one' => 1, 'two' => 2, 'three' => 3, 'four' => 4]);
$filtered = $array->filter(
	function ($item, $index, $key) {
		return strlen($key) >= 4;
	}
);
print_r($filtered);
// Expected output: JsArray ['three' => 3, 'four' => 4]

// Hybrid array example
$array = new JsArray(['one' => 1, 'two' => 2, 3, 4, 'five' => 5, 6]);
$filtered = $array->filter(
	function ($item) {
		return $item > 1;
	}
);
print_r($filtered);
// Expected output: JsArray ['two' => 2, 3, 4, 'five' => 5, 6]
// This is actually ['two' => 2, '0' => 3, '1' => 4, 'five' => 5, '2' => 6]

Syntax

$filteredArray = $array->filter($callback($item [, $index [, $key]]));

Parameters

  • $callback The user defined callback function which runs for every element. If this function returns True then the element is kept, otherwise the element is skipped.
    • $item The current element being processed in the array.
    • $index (optional) The zero based index number of the current processing element.
    • $key (optional) The key of the current processing element.

Return Value

JsArray instance with filtered elements.


# find

The find() method returns the value of the first element in the provided array that satisfied the user provided callback function. If it fails to find any value then it returns NULL

Example

$array = new JsArray([1, 2, 3, 2, 5, 5]);
$findValue = $array->find(
    function ($item) {
        return $item === 2;
    }
);
print_r($findValue);
// Expected output: 2

// With php >= 7.4 arrow function
$nonExistingValue = $array->find(fn($item) => $item === 20);
print_r($nonExistingValue);
// Expected output: NULL

Syntax

$findValue = $array->find($callback($item [, $index [, $key]]));

Parameters

  • $callback Function to execute to each element of the array. It has one required and two optional arguments.
    • $item The current Element of the array.
    • $index (optional) The zero based index of the current element of the array.
    • $key (optional) The key of the current element of the array.

Return Value

The value of the first element that is found by satisfying the user defined callback function. If no value found then NULL returns.


# findIndex

The findIndex() method returns the index of the first element in the provided array that satisfied the user provided callback function. If it fails to find any value then it returns -1

Example

$array = new JsArray([1, 2, 3, 2, 5, 5]);
$findValue = $array->findIndex(
    function ($item) {
        return $item === 2;
    }
);
print_r($findValue);
// Expected output: 1

// With php >= 7.4 arrow function
$nonExistingValue = $array->findIndex(fn($item) => $item === 20);
print_r($nonExistingValue);
// Expected output: -1

Syntax

$findIndex = $array->findIndex($callback($item [, $index [, $key]]));

Parameters

  • $callback Function to execute to each element of the array. It has one required and two optional arguments.
    • $item The current Element of the array.
    • $index (optional) The zero based index of the current element of the array.
    • $key (optional) The key of the current element of the array.

Return Value

The index of the first element that is found by satisfying the user defined callback function. If no value found then -1 returns.


# findLastIndex

The findLastIndex() method returns the index of the last element in the provided array that satisfied the user provided callback function. If it fails to find any value then it returns -1

Example

$array = new JsArray([1, 2, 3, 2, 5, 5]);
$findValue = $array->findLastIndex(
    function ($item) {
        return $item === 2;
    }
);
print_r($findValue);
// Expected output: 3

// With php >= 7.4 arrow function
$nonExistingValue = $array->findLastIndex(fn($item) => $item === 20);
print_r($nonExistingValue);
// Expected output: -1

Syntax

$findIndex = $array->findLastIndex($callback($item [, $index [, $key]]));

Parameters

  • $callback Function to execute to each element of the array. It has one required and two optional arguments.
    • $item The current Element of the array.
    • $index (optional) The zero based index of the current element of the array.
    • $key (optional) The key of the current element of the array.

Return Value

The index of the last element that is found by satisfying the user defined callback function. If no value found then -1 returns.


# flat

The flat() method creates a new array with all sub-array elements recursively concatenated into it. It converts multi-dimensional array into one-dimensional array.

Example

$array = new JsArray([1, 2, [3, 4, [5, 6], 7, 8]]);
$flatArray = $array->flat();
print_r($flatArray);
// Expected output: JsArray [1, 2, 3, 4, 5, 6, 7, 8]

Syntax

$flatArray = $array->flat();

Parameters

No parameter for this method

Return Value

JsArray instance with flatten one-dimensional array.


# forEach

The forEach() method executes a callable function for each item of the array.

Example

$array = new JsArray([1, 2, 3, 4]);
$array->forEach(
    function ($item, $index) {
        echo $index . " => " . $item . "\n";
    }
);

// Expected output:
// 0 => 1
// 1 => 2
// 2 => 3
// 3 => 4

Syntax

$array->forEach($callback($item [, $index [, $key]]));

Parameters

  • $callback

    • $item The current item being processed in the array.
    • $index (optional) A zero based index of the current item being processed in the array.
    • $key (optional) The key of the current item being processed in the array. This is useful for associative arrays.

Return Value

NULL


# JsArray::from

The JsArray::from static method responsible for creating a JsArray instance from given sequential array or string. This can also create an array if you provide a special associative array ['length' => integer_value].

Example

$array = JsArray::from([1, 2, 3, 4]);
print_r($array->get()); // Output: [1, 2, 3, 4]

$array = JsArray::from("foo");
print_r($array->get()); // Output: ['f', 'o', 'o'];

$array = JsArray::from(['length' => 4], fn($x, $i) => $i);
print_r($array->get()); // Output: [0, 1, 2, 3]

$array = JsArray::from([1, 2, 3], fn($x) => $x * 2);
print_r($array->get()); // Output: [2, 4, 6]

Syntax

$array = JsArray::from($iterable [, $callable]);

Parameters

  • $iterable The iterable array or string to convert to JsArray. The $iterable can contains either array or string. There may be a special associative array with providing length property by which you can generate an array with the length value.
  • $callable (optional) The map function to call on every item of the array.

Return Value

A JsArray Instance with generated array items.


# includes

The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate. This checks a loose equity for finding the value and for string it's case sensitive.

Example

$array = new JsArray([1, 2, 3, 4, 5, 6]);
$hasValue = $array->includes(3);
print_r($hasValue);
// Expected output: true

$hasNonExistingValue = $array->includes(2, 2);
print_r($hasNonExistingValue);
// Expected output: false

Syntax

$hasValue = $array->includes($item [, $fromIndex]);

Parameters

  • $item The item to find.
  • $fromIndex (optional) From which position finding starts. If this is omitted then searching begins from the index 0. If the $fromIndex is negative then its calculated like $length + $fromIndex. The $fromIndex value always lays within the range [0, $length].

Return Value

Boolean, True if the value included on the array, False otherwise.


# indexOf

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

Example

$array = new JsArray([1, 2, 3, 4, 5, 6]);
$position = $array->indexOf(4);
print_r($position);
// Expected output: 3

$notFoundingPosition = $array->indexOf(2, 3);
print_r($notFoundingPosition);
// Expected output: -1

Syntax

$position = $array->indexOf($item [, $fromIndex]);

Parameters

  • $item The item to find.
  • $fromIndex (optional) From which position finding starts. If this is omitted then searching begins from the index 0. If the $fromIndex is negative then its calculated like $length + $fromIndex. The $fromIndex value always lays within the range [0, $length].

Return Value

Integer, The index of the searching item. The index is zero based and if the item is not found then returns -1.


# join

The join() method creates and returns a new string by concatenating all of the elements in an array, separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.

Example

$array = new JsArray([1, 2, 3, 4, 5, 6]);
$str = $array->join();
print_r($str);
// Expected output: "1,2,3,4,5,6"

$str = $array->join(' + ');
print_r($str);
// Expected output: "1 + 2 + 3 + 4 + 5 + 6"

Syntax

$str = $data->join([$separator]);

Parameters

  • $separator (optional) Specifies a string to separate each pair of adjacent elements of the array. If omitted, the array elements are separated with a comma (","). If separator is an empty string, all elements are joined without any characters in between them.

Return Value

String, the string after joining the array elements with the help of $separator.


# keys

The keys() method creates a new array with the keys of the array.

Example

$array = new JsArray([1, 2, 3, 4, 5]);
$keys = $array->keys();
print_r($keys);
// Expected output: JsArray [0, 1, 2, 3, 4]

$assocArray = new JsArray(['one' => 1, 'two' => 2, 'three' => 3]);
$keys = $assocArray->keys();
print_r($keys);
// Expected output: JsArray ['one', 'two', 'three']

Syntax

$keys = $array->keys();

Parameters

No parameter for this method.

Return Value

JsArray instance with the keys of the provided array. It allows chaining.


# map

The map() method creates a new array populated by the user callback function on every element of the calling array. It keeps the original array untouched.

Example

$array = new JsArray([1, 2, 3, 4, 5]);
$binaryArray = $array->map(
    function ($item, $index) {
        return $item % 2;
    }
);

print_r($binaryArray);
// Expected output: JsArray [1, 0, 1, 0, 1]

// PHP >= 7.4 you can use arrow function.
$binaryArray = $array->map(fn($item, $index) => $item % 2);
// Output remains same.

Syntax

$newArray = $array->map($callback($item [, $index [, $key]]));

Parameters

  • $callback This is a callable function which is executed on every element of the $array and the return value of the function is added to the $newArray.

    The $callback function takes one required and two optional arguments.

    • $item The current item being processed in the array.
    • $index (optional) A zero based index of the current item being processed in the array.
    • $key (optional) The key of the current item being processed in the array. This is useful for associative arrays.

Return Value

A new JsArray instance after each item being processed by the callback function.


# pop

The pop() method removes the last element from an array and returns this element. This method changes the original array.

Example

$array = new JsArray([1, 2, 3, 4, 5]);
$removed = $array->pop();
print_r($removed);
// Expected output: 5

print_r($array);
// Expected output: JsArray [1, 2, 3, 4]

Syntax

$removed = $array->pop();

Parameters

No parameter for this method.

Return Value

The removed element from the array.


# push

The push() method adds a new element at the end of an array. This method changes the original array.

Example

$array = new JsArray([1, 2, 3, 4]);
$length = $array->push(5);
print_r($length);
// Expected output: 5

print_r($array);
// Expected output: JsArray [1, 2, 3, 4, 5]

$newLength = $array->push(5, 6, 8);
print_r($newLength);
// Expected output: 8

print_r($array);
// Expected output: JsArray [1, 2, 3, 4, 5, 6, 7, 8]

Syntax

$length = $array->push([$item1 [, ...[, $itemN]]);

Parameters

-$itemN The item(s) to add to the end of the array.

Return Value

Integer, The length of the array after pushing the items.


# reduce

The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in single output value.

Example

$array = new JsArray([1, 2, 3, 4, 5]);
$sum = $array->reduce(
    function($acc, $curr) {
        return $acc + $curr;   
    },
    0
);
print_r($sum);
// Expected output: 15

// Using php >= 7.4 arrow function
$sum = $array->reduce(fn($acc, $curr) => $acc + $curr, 0);
print_r($sum);
// Expected output: 15

Syntax

$result = $array->reduce($callback($accumulator, $currentValue [, $index [, $key]])[, $initial]);

Parameters

  • $callback The user defined callback function which is executed for every element (except for the first if no $initial value is given) of the array. It takes two required and two optional arguments.
    • $accumulator The accumulator accumulates callback's return values. It is the accumulated value previously returned in the last invocation of the callback—or $initial value, if it was supplied (see below).
    • $currentValue The current element being processed in the array.
    • $index (optional) The index of the current element being processed in the array. Starts from index 0 if an $initial value is provided. Otherwise, it starts from index 1.
    • $key (optional) The key of the current element being processed in the array. Starts from index 0 key if an $initial value is provided. Otherwise, it starts from index 1 key.
  • $initial (optional) A value to use as the first argument to the first call of the callback. If no $initial value is supplied, the first element in the array will be used as the initial accumulator value and skipped as $currentValue.

Return Value

The single value that results from the reduction. If the returned value is an array then the array converted into an instance of JsArray for chaining. __

# reverse

The reverse() method reverses an array in place. The first array element becomes the last, and the last array element becomes the first.

Example

$array = new JsArray([1, 2, 3, 4, 5]);
$array->reverse();

print_r($array);
// Expected output: JsArray [5, 4, 3, 2, 1]

Syntax

$array->reverse();

Parameters

No parameter for this method.

Return Value

The reversed array. The array is also an instance of JsArray for chaining.


# shift

The shift() method removes the first element from an array and returns that removed element. This method changes the original array.

Example

$array = new JsArray([1, 2, 3, 4, 5]);
$removed = $array->shift();

print_r($removed);
// Expected output: 1

print_r($array);
// Expected output: JsArray [2, 3, 4, 5]

Syntax

$removed = $array->shift();

Parameters

No parameter for this method.

Return Value

The removed element from the array; NULL if the array is empty.


# slice

The slice() method returns a copy of a portion of an array into a new array selected from the range [$start to $end) ($end not included) where $start and $end represent the index of items in that array. The original array will not be modified.

Example

$array = new JsArray([1, 2, 3, 4, 5]);
$sliced = $array->slice(1, 4);

print_r($sliced);
// Expected output: JsArray [2, 3, 4]

$sliced = $array->slice(-3);
print_r($sliced);
// Expected output: JsArray [3, 4, 5]

Syntax

$sliced = $array->slice([$start [, $end]]);

Parameters

  • $start (optional) Zero-based index at which to start extraction. A negative index can be used, indicating an offset from the end of the sequence. slice(-2) extracts the last two elements in the sequence.

    If $start is NULL or empty, slice starts from the index 0.

    If $start is greater than the index range of the sequence, an empty array is returned.

  • $end (optional) Zero-based index before which to end extraction. slice extracts up to but not including end. For example, slice(1, 4) extracts the second element through the fourth element (elements indexed 1, 2, and 3).

    A negative index can be used, indicating an offset from the end of the sequence. slice(2,-1) extracts the third element through the second-to-last element in the sequence.

    If $end is omitted, slice extracts through the end of the sequence ($array->length).

    If $end is greater than the length of the sequence, slice extracts through to the end of the sequence ($array->length).

Return Value

A new JsArray instance containing the extracted elements.


# some

The some() method tests whether at least one element in the array passes the test implemented by the user provided callback function. It returns a Boolean value.

Example

$array = new JsArray(['one' => 1, 'two' => 2, 'three' => 3, 'four' => 4]);
$passed = $array->some(
    function ($item, $index, $key) {
        return strlen($key) > 4;
    }
);
var_dump($passed);
// Expected output: bool(true)

// Using php >= 7.4 arrow function
$notPassed = $array->some(fn($item, $index, $key) => strlen($key) < 3);
var_dump($notPassed);
// Expected output: bool(false)

Syntax

$passed = $array->some($callback($item [, $index [, $key]]));

Parameters

  • $callback A function to test for each element, taking three arguments:
    • $item The current element being processed in the array.
    • $index (optional) The index of the current element being processed in the array.
    • $key (optional) The key of the current element being processed in the array.

Return Value

true if the $callback function returns a truthy value for at least one element in the array. Otherwise, false.


# sort

The sort() method sorts the elements of an array in place and returns the sorted array. The default sort order is ascending. Currently, the sort has been done by using merge sort implementation.

Example

$array = new JsArray([2, 4, 2, 1, 6, 7, 9]);
$array->sort();
print_r($array);
// Expected output: JsArray [1, 2, 2, 4, 6, 7, 9]

// Sort descending order
$array = new JsArray([2, 4, 2, 1, 6, 7, 9]);
$array->sort(
    function ($a, $b) {
        return $b - $a;
    }
);
print_r($array);
// Expected output: JsArray [9, 7, 6, 4, 2, 2, 1]

Syntax

$array->sort([$callback($firstEl, $secondEl)]);

Parameters

  • $callback Specifies a function that defines the sort order. If it is omitted then the elements are sorted in ascending order.

    • $firstEl The first element for comparison.
    • $secondEl The second element for comparison.

Return Value

The original JsArray instance with sorted data. This method changes the original array.


# splice

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.

Example

$array = new JsArray(['mango', 'orange', 'banana']);
$deletedItems = $array->splice(1, 1);
print_r($deletedItems);
// Expected output: JsArray ['orange']

print_r($array);
// Expected output: JsArray ['mango', 'banana']

// Insert new item without deleting
$delete = $array->splice(0, 0, 'lemon', 'apple');
print_r($array);
// Expected output: JsArray ['lemon', 'apple', 'mango', 'banana']

print_r($delete);
// Expected output: JsArray []

Syntax

$deletedItems = $array->splice([$start [, $deleteCount [, $item1 [, ...[, $itemN]]]]]);

Parameters

  • $start (optional) The index at which to start changing the array. If greater than the length of the array, start will be set to the length of the array. In this case, no element will be deleted but the method will behave as an adding function, adding as many element as item[n*] provided. If negative, it will begin that many elements from the end of the array. (In this case, the origin -1, meaning -n is the index of the nth last element, and is therefore equivalent to the index of $array->length - n.) If $array->length + $start is less than 0, it will begin from index 0.

  • $deleteCount (optional) An integer indicating the number of elements in the array to remove from $start. If $deleteCount is omitted, or if its value is equal to or larger than $array->length - $start (that is, if it is equal to or greater than the number of elements left in the array, starting at start), then all the elements from start to the end of the array will be deleted.

  • $itemN (optional) The elements to add to the array, beginning from $start. If you do not specify any elements, splice() will only remove elements from the array.

Return Value

An instance of JsArray with the deleted items.