PHP: ActionScript Array.slice method


In ActionScript, to slice an array, we use Array.slice method:

public slice([startIndex: Number], [endIndex: Number]) : Array

Returns a new array that consists of a range of elements from the original array, without modifying the original array. The returned array includes the startIndex element and all elements up to, but not including, the endIndex element.

Now, we make the similar method in PHP:

function array_slice2($array,$startIndex=false , $endIndex=false){
    if($endIndex===false || $endIndex<0) $endIndex += count($array);
    return array_slice($array,$startIndex,$endIndex-$startIndex);
}

Example:

$array =  Array("banana", "tomato", "orange", "apple", "watermelon");
var_dump(array_slice2($array));
var_dump(array_slice2($array,1));
var_dump(array_slice2($array,1,3));
var_dump(array_slice2($array,-2));
var_dump(array_slice2($array,2,-2));

Result:

array(5) {
  [0]=>
  string(6) "banana"
  [1]=>
  string(6) "tomato"
  [2]=>
  string(6) "orange"
  [3]=>
  string(5) "apple"
  [4]=>
  string(10) "watermelon"
}
array(4) {
  [0]=>
  string(6) "tomato"
  [1]=>
  string(6) "orange"
  [2]=>
  string(5) "apple"
  [3]=>
  string(10) "watermelon"
}
array(2) {
  [0]=>
  string(6) "tomato"
  [1]=>
  string(6) "orange"
}
array(2) {
  [0]=>
  string(5) "apple"
  [1]=>
  string(10) "watermelon"
}
array(1) {
  [0]=>
  string(6) "orange"
}

Note: In PHP, we have the function array_slice, but two methods have different usage.

Part 2: ActionScript vs Javascript:
Javascript method Array.prototype.slice() is the same with ActionScript method Array.slice

Javascript syntax:

arr.slice([begin[, end]])

The slice() method returns a shallow copy of a portion of an array into a new array object.

Example 2:

var $array = ["banana", "tomato", "orange", "apple", "watermelon"];
alert($array.slice());
alert($array.slice(1));
alert($array.slice(1, 3));
alert($array.slice(-2));
alert($array.slice(2, -2));

Result: https://jsfiddle.net/sans_amour/keju8t94/

Leave a Reply